<?php
include dirname(__FILE__).'/index/common/function.php'; //杨柳  引入函数
use EasyWeChat\Factory;
use think\Db;
//use think\Log;
// 公共助手函数
function getRedis(){
    try{
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);//serverip port
        $redis->select(1);
        return $redis;
        //抛出异常
    } catch (Exception $e) {
        echo $e->getMessage();
        // die(); // 终止异常
    }
}
//生成合同号
if (!function_exists('DeleteContractFile')) {
  
   function DeleteContractFile($info){
    if(!$info) return false;
      foreach ($info as $key => $value) {
         $file = '';
        switch ($key) {
          case 'sign_url':
            $file = ROOT_PATH.'public'.$value;  
            break;
           case 'contract_url':
           case 'contract_all_url':
           case 'contract_blank_url':
            $value = str_replace('https://oa.fc62.com','',$value);
            $file = ROOT_PATH.'public'.$value;
           break;   
        }
        if($file && file_exists($file)){
           @unlink($file);
        }
      }
      return true;
    }
}
//生成合同号
if (!function_exists('func_new_each')) {
  
   function func_new_each(&$array){
      $res = array();
      $key = key($array);
      if($key !== null){
          next($array);
          $res[1] = $res['value'] = $array[$key];
          $res[0] = $res['key'] = $key;
      }else{
          $res = false;
      }
      return $res;
    }
}
//生成合同号
if (!function_exists('GenerateContractNo')) {
  
    function GenerateContractNo($info = [],$pid = '464' ,$type = 'add'){
        $model = new \app\admin\model\halt\Cate;
        $Serialmodel = new \app\common\model\Serial;
       
        $result = false;
        if($type == 'add'){
           $product_info = $model::where(['pid'=>$pid,'name'=>$info['edition_txt']])->find();
          if(!$product_info) return false;
          if(strpos($info['medium'],'光盘') !== false){
             $medium = '光盘';
          }elseif(strpos($info['medium'],'微盘') !== false){
            $medium = '微盘';
          }
          if(!isset($medium)) return false;
          $medium_info = $model::where(['pid'=>$product_info->id,'name'=>$medium])->find();
          if(!$medium_info) return false;
          $data = [
                  'code'=>RepeatContractNo(),
                  'order_sn'=>$info['order_sn'],
                  'product'=>$pid,
                  'kemu'=>$product_info->id,
                  'banben'=>$medium_info->id,
                  'send'=>1,
                  'sendtime'=>time(),
                  'kaoshi'=>$info['province_text'],
                  'type'=>rtrim($pid.','.$product_info->id.','.$medium_info->id,','),
                  'fahuo'=>$info['province_text'].' '.$info['city_text'].' '.$info['area_text'].' '.$info['address'],
                  'dealer_uid'=>81,
                  //'subject'=>$info['subject']
             ];
           $result = $Serialmodel->save($data);
        }else if($type == 'edit'){
          $data = [
                'kaoshi'=>$info['province_text'],
                'fahuo'=>$info['province_text'].' '.$info['city_text'].' '.$info['area_text'].' '.$info['address'],
                //'subject'=>$info['subject']
           ];
          $result =  $Serialmodel->where(['code'=>$info['contract_no']])->update($data);
          $data['code'] = $info['contract_no'];
        }
       if($result){
             tf2020_code($info,$data['code'],$type);
            return $data['code'];
       }else{
           return false;
       }

  
    }
}
//添加合同信息
if (!function_exists('tf2020_code')) {

    function tf2020_code($info,$code,$type = 'add'){
        
        $data = array();
    
        $data['bianhao'] = GetBanHaoInfo()[$info['edition_txt']][$info['province_text']]??'';
        $data['xuesheng'] = $info['student_name'];
        $data['jiazhang'] = $info['parent_name'];
        $data['xingbie'] = $info['gender'] == 1 ? "男" : "女";
        $data['lianxi'] = $info['phone'];
        $data['guding'] = $info['tel'];
        $data['xuexiao'] = $info['grade'];
        $data['dizhi'] = $info['province_text'].' '.$info['city_text'].' '.$info['area_text'].' '.$info['address'];
        $data['chengji'] = $info['last_exam'];
        $data['shenfen'] = $info['id_card'];
        $data['end_time'] = $info['closing_date'];
        $tf2020_send = Db::connect([
            // 数据库类型
            'type'        => 'mysql',
            // 服务器地址
            'hostname'    => '42.96.177.38',
            // 数据库名
            'database'    => 'tf2020',
            // 数据库用户名
            'username'    => 'wangmeng',
            // 数据库密码
            'password'    => 'wangmeng',
            // 数据库编码默认采用utf8
            'charset'     => 'utf8',
        ]);
        $result = false;
        if($type == 'add'){
            $data['daima'] = $code;
            $data['order_sn'] = $info['order_sn'];
            if($info['edition_txt']=="全国版文科" || $info['edition_txt']=="江苏版文科"){
                $data['subject'] = str_replace("数学",'文数',$info['subject']);
            }elseif($info['edition_txt']=="全国版理科" || $info['edition_txt']=="江苏版理科"){
                $data['subject'] = str_replace("数学",'理数',$info['subject']);
            }else{
                $data['subject'] = $info['subject'];
            }
            $data['kemu'] = '';
            $data['username'] = '';
            $data['inputtime'] = time();
            if(strpos($info['medium'],'光盘') !== false){
                $data['ks_category'] = '光盘版';
            }elseif(strpos($info['medium'],'微盘') !== false){
                $data['ks_category'] = 'U盘版';
            }
            $data['year'] = 2021;
            $data['classes'] = "提分宝典";
           $result = $tf2020_send->table("tf_hetong")->insert($data);
        }else if($type == 'edit'){
          $result = $tf2020_send->table('tf_hetong')->where('daima', $code)->update($data);
        }
        if($result){
          return true;
        }
        return false;
    }
}
//查询合同编号是否重复
if (!function_exists('GetBanHaoInfo')) {
  
    function GetBanHaoInfo(){
       $bianhao = array(
            "北京版"=>array("北京"=>'1010'),
            "上海版"=>array("上海"=>'2017'),
            "浙江版"=>array("浙江"=>'3117'),
            "新高考版"=>array(
                "山东"=>'2510',
                "天津"=>'3010',
                "海南"=>'5710',
                "河北"=>'0510',
                "辽宁"=>'1110',
                "福建"=>'3510',
                "湖北"=>'4310',
                "湖南"=>'4110',
                "广东"=>'5110',
                "重庆"=>'4010',
            ),
            "江苏版文科"=>array("江苏"=>'2110'),
            "江苏版理科"=>array("江苏"=>'2120'),
            "全国版文科"=>array(
                "内蒙古"=>'0110',
                "山西"=>'0310',
                "吉林"=>'1310',
                "黑龙江"=>'1510',
                "江西"=>'1610',
                "安徽"=>'2310',
                "河南"=>'4510',
                "广西"=>'5310',
                "贵州"=>'5510',
                "四川"=>'6110',
                "云南"=>'6510',
                "陕西"=>'7110',
                "甘肃"=>'7310',
                "宁夏"=>'7510',
                "青海"=>'8110',
                "新疆"=>'8310',
                "西藏"=>'8510',
            ),
            "全国版理科"=>array(
                "内蒙古"=>'0120',
                "山西"=>'0320',
                "吉林"=>'1320',
                "黑龙江"=>'1520',
                "江西"=>'1620',
                "安徽"=>'2320',
                "河南"=>'4520',
                "广西"=>'5320',
                "贵州"=>'5520',
                "四川"=>'6120',
                "云南"=>'6520',
                "陕西"=>'7120',
                "甘肃"=>'7320',
                "宁夏"=>'7520',
                "青海"=>'8120',
                "新疆"=>'8320',
                "西藏"=>'8520',
            ),
        );
       return $bianhao;
    }
}
//查询合同编号是否重复
if (!function_exists('RepeatContractNo')) {
  
    function RepeatContractNo(){
        $code = '2'.random_code(12);
        if(\app\common\model\Serial::where('code',$code)->where('is_cancel',0)->count()){
          return RepeatContractNo();
        }else{
          return $code;
        }
    }
}
if (!function_exists('combineURL')) {
  
    function combineURL($baseURL,$keysArr){
        $combined = $baseURL."/";
        $valueArr = array();

        foreach($keysArr as $key => $val){
            $valueArr[] = "$val";
        }

        $keyStr = implode("/",$valueArr);
        $combined .= ($keyStr);
        return $combined;
    }
}
if (!function_exists('update_url')) {
  
   function update_url($url = '',$path = '/uploads/tool/hb/erweima/'){
        if(!$url) return false;
        $file_name = date('YmdHis') . uniqid().'.png';
        $file = ROOT_PATH.'public'.$path.$file_name;
        $dir_name = dirname($file);
         //目录不存在就创建
        if(!file_exists($dir_name)) {
            //iconv防止中文名乱码
           $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        file_put_contents($file, file_get_contents($url));
        return $path.$file_name;
        
    }
}
if (!function_exists('check_public')) {
  /*
  * 公共审核
  * @param int $tyoe 类型   1=分公司 2=代理商
  * @param int $step 步骤   1 2 3 4 这样
  * @param int $action 动作   1=判断权限并发送  2获取userid并发送
  * @return boolean|int
  //权限 role_type   1=上级 isleader 2=对接人 docking 3=指定人员    4=角色
  权限内容 role_value
  */
    function check_public($orderID = NULL,$action = 2,$auth = NULL,$save = []){
      if(!$orderID||!$auth) return false;
      $order_info = \app\common\model\order\Order::get($orderID);
      $array = \think\Config::get('review.check');
      //print_r($agent->dep_text);die;
      //print_r($auth->id);die;
      $step_arr = $array[$order_info->sorter]['step'][$order_info->step];
      $userList = '';
      $totag = '';
      $type = 1;
         if($order_info->sorter == 1){
           $agent = \app\admin\model\Githouse::get(array('id'=>$order_info['dep_id']));
            switch ($step_arr['role_type']) {
               //step = 1
               case 1: 

                  if($action == 1){
                        //判断此步骤权限
                       if(!$auth->isleader){
                           return false;
                        }
                      //是否修改
                      if($save){
                        if($save['save'] == 1){
                          $userList =  $array[$order_info->sorter]['step'][2]['role_value'];
                        }
                      }
                  }
                  if($action == 2){
                    if($auth->isleader){
                       $save['step'] = 2;
                       $userList = $array[$order_info->sorter]['step'][2]['role_value'];
                    }else{
                        //获取上级userid
                        $userList = TableListSqlQuery('Admin',"find_in_set('".$auth->department."',department) and `isleader` = '1' ",'userid');
                        $userList = implode('|',array_column($userList,'userid'));
                    }
                  }
                break; 
               //step = 2
              case 2:
                if($action == 1){
                  if($array[$order_info->sorter]['step'][2]['role_value'] != $auth->userid){
                    return false;
                 }
                   //是否修改
                  if($save){
                    if($save['save'] == 1){
                      $userList = $array[$order_info->sorter]['step'][3]['role_value'];
                    }
                  }
                }
                break;
                //step = 3
              case 3:
                 if($array[$order_info->sorter]['step'][3]['role_value'] != $auth->userid){
                    return false;
                 }
                   //是否修改
                  if($save){
                    if($save['save'] == 1){
                      $userList = $array[$order_info->sorter]['step'][4]['role_value'];
                      //$totag = $array[$order_info->sorter]['step'][4]['role_value'];
                    }
                  }
                break;
                 //step = 4
              case 4:
                  if($action == 1){
                   if($array[$order_info->sorter]['step'][4]['role_value'] != $auth->userid){
                    return false;
                  }
                    // if(!in_array($step_arr['role_value'],$auth->group_id)){
                    //   return false;
                    // }
                     //是否修改
                    if($save){
                      if($save['save'] == 1){
                         $save['status'] = 2;
                         $type = 3;
                         $userList = $order_info->userid;
                         //通知发货
                         check_send('',$array[$order_info->sorter]['step']['5']['role_value'],$agent,$order_info,4);
                      }
                    }
                  }
                break;  
               //step = 5
              case 5:
                  if($action == 1){
                    if(!in_array($step_arr['role_value'],$auth->group_id)){
                      //return false;
                    }
                     //是否修改
                    if($save){
                      if($save['save'] == 1){
                         $type = 5;
                         $save['deliverystatus'] = 1;
                         $save['action'] = '已发货';
                         $userList = $order_info->userid;
                      }
                      if($save['save'] == 2){
                        $save['action'] = '发货已驳回';
                      }
                    }
                  }
                break;  
             case 6:
            return false;
                break; 
              default:
                break;
            }
            if($action == 6){
                   //抄送
               $userList = str_replace(',','|',$agent->docking).'|HanXiaoFang';
               $userList = 'GaoZhenYu';
               $type = 6;
            }
        }
        if($order_info->sorter == 2){

        }
         //是否修改
          if($save){
             $save['save'] =  isset($save['save'])?$save['save']:0;
            if($save['save'] == 1){
              $save['step'] = $step_arr['role_type']+1;
              $save['action'] = isset($save['action'])?$save['action']:'已通过';
            }
            if($save['save'] == 2){
              $save['step'] = 1;
              $save['status'] = -1;
              $save['action'] = isset($save['action'])?$save['action']:'已驳回';
              $type = 2;
              $userList = $order_info->userid;
            }
          }
        //上线注释
        
         //print_r($totag);die;
        if($save) check_update($orderID,$auth,$save);
        if($userList || $totag) check_send($userList,$totag,$agent,$order_info,$type);
        
        return true;
    }
}
if (!function_exists('imgno')) {
  /*
  * 公共审核修改
  */
    function imgno($img){
        return $img?:'/nopic.jpg';
    }
}if (!function_exists('check_update')) {
  /*
  * 公共审核修改
  */
    function check_update($orderID = NULL,$auth = NULL,$arr = []){
       $order = \app\common\model\order\Order::get($orderID);
       if(isset($arr['status'])) $order->status = $arr['status'];
       if(isset($arr['step'])) $order->step = $arr['step'];
       if(isset($arr['deliverystatus'])) $order->deliverystatus = $arr['deliverystatus'];
       if(isset($arr['deliverys_image'])) $order->deliverys_image = $arr['deliverys_image'];
       if(isset($arr['delivery_id'])) $order->delivery_id = $arr['delivery_id'];
       $order->save();
       if(isset($arr['action'])){
         //提交订货单日志
          $log = \app\common\model\order\Orderlog::create([
              'order_id'=>$orderID,
              'userid'=>$auth->userid,
              'dep_id'=>$order->dep_id,
              'dep_name'=>'',
              'username'=>$auth->username,
              'content'=>$arr['content'],
              'action'=>$arr['action'],
              'type'=>1,
          ]);
        }
        return true;
    }
}
if (!function_exists('check_send')) {
  /*
  * 公共审核发送
  */
    function check_send($userList = '',$totag = '',$agent = NULL,$order = NULL,$type = 1){
        $orderID = $order->id;
        $array = [];
        $array[1] = [
            'touser'=>$userList,
            'toparty'=>'',//部门
            'totag'=>$totag,//标签
            'description'=>'【'.$agent->dep_text.'】仓库下单完成，请审核',
            'urlInfo'=>"http://{$_SERVER['SERVER_NAME']}/index/agent/details/orderID/{$orderID}",
            'title'=>'要货订单审核',
        ];
        $array[2] = [
            'touser'=>$userList,
            'toparty'=>'',//部门
            'totag'=>$totag,//标签
            'description'=>$order->nb.' 审核未通过，请查看',
            'urlInfo'=>"http://{$_SERVER['SERVER_NAME']}/agent/shopping/checkOrder/id/{$orderID}",
            'title'=>'您提交的订单审核未通过',
        ];
        $array[3] = [
            'touser'=>$userList,
            'toparty'=>'',//部门
            'totag'=>$totag,//标签
            'description'=>$order->nb.' 审核通过，请查看',
            'urlInfo'=>"http://{$_SERVER['SERVER_NAME']}/agent/agent/order",
            'title'=>'您提交的订单审核通过',
        ];
        $array[4] = [
            'touser'=>$userList,
            'toparty'=>'',//部门
            'totag'=>$totag,//标签
            'description'=>'【'.$agent->dep_text.'】审核完成，请发货',
            'urlInfo'=>"http://{$_SERVER['SERVER_NAME']}/index/agent/details/orderID/{$orderID}",
            'title'=>'要货订单发货',
        ];
        $array[5] = [
            'touser'=>$userList,
            'toparty'=>'',//部门
            'totag'=>$totag,//标签
            'description'=>$order->nb.' 已经发货',
            'urlInfo'=>"http://{$_SERVER['SERVER_NAME']}/agent/agent/order",
            'title'=>'您提交的订单已发货',
        ];
        $array[6] = [
            'touser'=>$userList,
            'toparty'=>'',//部门
            'totag'=>$totag,//标签
            'description'=>'【'.$agent->dep_text.'】仓库的要货单',
            'urlInfo'=>"http://{$_SERVER['SERVER_NAME']}/index/agent/details/orderID/{$orderID}",
            'title'=>'要货订单抄送',
        ];
        $newFlow = new \workflow\workflow();
        return $newFlow->send_work('textcard',$array[$type]);
    }
}
if (!function_exists('check_plan_public')) {
  /*
  * 计划审核权限判断
  * @param int $type 类型   1=判断访问/审核权限 2提交并抄送  3审核并抄送
  * @param array $auth 登录信息
  * @param array $extract_week 周id
  * @param int $action 动作   1=判断权限并发送  2获取userid并发送
  * @param array $save 保存信息
  * @return boolean|int
  权限内容 role_value
  */
    function check_plan_public($type = 1,$auth = NULL,$extract_week = NULL,$save = []){
          switch ($type) {
            case 1:
              if($true =\think\Cookie::get('plan_auth')){
                 return $true;
               }
               $true = 0;
               $arr = ['copy_person'=>0,'auditor'=>0,'add'=>0,'department'=>0];
               //$arr = ['copy_person'=>1,'auditor'=>1,'add'=>1,'department'=>0];
               if(ValueExists($auth->userid,config('site.plan_copy_person'),'|')){
                  $arr['copy_person'] = 1;
                  $true++;
               }       
               if(ValueExists($auth->userid,config('site.plan_Auditor'),'|')){
                  $arr['auditor'] = 1;
                  $true++;
               }  
               if($department = check_Department($auth->department)){
                 $arr['department'] = $department;
                 $true++;
               }
               if($auth->check('plan/add') && $department){
                  $arr['add'] = 1;
                  $true++;
               }
               if($true){
                  \think\Cookie::set('plan_auth', $arr);
                 return $arr;
               }else{
                 return false;
               }
              break;         
           case 2:
           if(!$extract_week) return false;
             $plan_info = \app\admin\model\finance\extract\Week::get($extract_week);
             $copy_person = config('site.plan_copy_person');
             //上线注释
             //$copy_person = 'GaoZhenYu';
             check_plan_send($copy_person,'',$plan_info,1);
             $auditor = config('site.plan_Auditor');
             //上线注释
              //$auditor = 'GaoZhenYu';
              check_plan_send($auditor,'',$plan_info,2);
              return true;
              //是否修改
             break;
          case 3:
           if(!$extract_week) return false;
             $plan_info = \app\admin\model\finance\extract\Week::get($extract_week);
              if(!ValueExists($auth->userid,config('site.plan_Auditor'),'|')){
                  return false;
               }  
               $userList ='';
             //是否修改
              if($save){
                 $save['save'] =  isset($save['save'])?$save['save']:0;
                if($save['save'] == 1){
                   $save['status'] = 2;
                   $save['action'] = isset($save['action'])?$save['action']:'初审·已通过';
                   $type = 4;
                   $userList = $plan_info->publish;
                }
                if($save['save'] == 2){
                  $save['status'] = -1;
                  $save['action'] = isset($save['action'])?$save['action']:'初审·已驳回';
                  $type = 3;
                  $userList = $plan_info->publish;
                }
              }
             //上线注释
              //$userList = $userList?'GaoZhenYu':'';
             //print_r($totag);die;
              if($save) check_plan_update($extract_week,$auth,$save);
              if($userList) check_plan_send($userList,'',$plan_info,$type);
              break;
            default:
              break;
          }
      
        return true;
    }
}
if (!function_exists('check_plan_update')) {
  /*
  * 公共审核修改
  */
    function check_plan_update($extract_week = NULL,$auth = NULL,$arr = []){
       $plan_info = \app\admin\model\finance\extract\Week::get($extract_week);
       if(isset($arr['status'])){

         $plan_info->status = $arr['status'];
         if($arr['status'] == 2){
              //成功后生成周相关数据
               list($true,$lecturer_id) = GenerateWeek($extract_week);
               $plan_info->lecturer_id = $lecturer_id;
            }
       }
       $plan_info->save();
       if(isset($arr['action'])){
         //提交订货单日志
          $log = \app\admin\model\finance\extract\Weeklog::create([
              'extract_week'=>$extract_week,
              'userid'=>$auth->userid,
              'dep_id'=>$plan_info->department,
              'username'=>$auth->username,
              'content'=>$arr['content'],
              'action'=>$arr['action'],
              'type'=>$arr['save'],
          ]);
        }
        return true;
    }
}
if (!function_exists('check_plan_send')) {
  /*
  * 计划审核发送
  */
    function check_plan_send($userList = '',$totag = '',$plan_info = NULL,$type = 1){
        $Api = new \app\common\controller\Api;
        //获取默认值new \workflow\workflow()
        $config = $Api->getConfig($Api->getDefault('Plan'));
        $ids = $plan_info->id;
        $array = [];
        $array[1] = [
            'description'=>$plan_info->username_text.'抄送了【'.$plan_info->department_text.'】第'.$plan_info->week.'周开会计划给您',
            'url'=>"http://{$_SERVER['SERVER_NAME']}/index/plan/view/ids/{$ids}",
            'title'=>'报计划查看',
        ];
        $array[2] = [
         
            'description'=>$plan_info->username_text.'提交了【'.$plan_info->department_text.'】 第'.$plan_info->week.'周开会计划给你，请审核',
            'url'=>"http://{$_SERVER['SERVER_NAME']}/index/plan/details/ids/{$ids}",
            'title'=>'报计划审核',
        ];
        $array[3] = [
           
            'description'=>'【'.$plan_info->department_text.'】 第'.$plan_info->week.'周开会计划 审核未通过，请查看',
            'url'=>"http://{$_SERVER['SERVER_NAME']}/index/plan/edit/ids/{$ids}",
            'title'=>'报计划审核',
        ];
        $array[4] = [
            'description'=>'【'.$plan_info->department_text.'】 第'.$plan_info->week.'周开会计划 审核已通过，请查看',
            'url'=>"http://{$_SERVER['SERVER_NAME']}/index/plan/view/ids/{$ids}",
            'title'=>'报计划查看',
        ];
       /* $array[5] = [
            'touser'=>$userList,
            'toparty'=>'',//部门
            'totag'=>$totag,//标签
            'description'=>$order->nb.' 已经发货',
            'urlInfo'=>"http://{$_SERVER['SERVER_NAME']}/agent/agent/order",
            'title'=>'您提交的订单已发货',
        ];*/
         return pushMsgText($config,"textcard",$array[$type],$userList,'',$totag);
    }
}
if (!function_exists('check_books_public')) {
  /*
  * 计划审核权限判断
  * @param int $type 类型   1=判断访问/审核权限 2提交并抄送  3审核并抄送
  * @param array $auth 登录信息
  * @param array $extract_week 周id
  * @param int $action 动作   1=判断权限并发送  2获取userid并发送
  * @param array $save 保存信息
  * @return boolean|int
  权限内容 role_value
  */
    function check_books_public($type = 1,$auth = NULL,$extract_week = NULL,$save = []){
          switch ($type) {
            case 1:
              if($true =\think\Cookie::get('books_auth')){
                return $true;
               }
                $true = 0;
                $arr = ['all'=>0,'add'=>0,'edit'=>0,'del'=>0,'department'=>''];
                //上线注释
               //$arr = ['all'=>1,'add'=>1,'edit'=>1,'del'=>1,'department'=>'31'];
               //$true = 1;
                if($auth->check('see/index')){
                    if($auth->check('see/all')){
                      $arr['all'] = 1;
                      $true++;
                    }
                    if($department = check_Department($auth->department)){
                         $arr['department'] = $department;
                         $true++;
                    }
                    if($auth->check('finance/extract/week/books_add')){
                       $arr['add'] = 1;
                       $true++;
                    } 
                    if($auth->check('finance/extract/week/books_edit')){
                       $arr['edit'] = 1;
                       $true++;
                    }  
                     if($auth->check('finance/extract/week/books_delete')){
                       $arr['del'] = 1;
                       $true++;
                    }
                }
               if($true){
                 \think\Cookie::set('books_auth', $arr);
                 return $arr;
               }else{
                 return false;
               }
              break;         
            default:
              break;
          }
      
        return true;
    }
}
if (!function_exists('check_Department')) {
  /*
  * 判断所属公司
  * @param array  username   用户信息
  * @param array $type 返回类型 1 返回第一个id  2 返回列表
  * @param array $save 保存信息
  */
    function check_Department($department,$type = 1){
      $model = new \app\admin\model\AuthDepartment;
      $parentid = $parentid_2 = $parentid_3 = [];
      $parentid =  $model::where('id','in',$department)->field('parentid,delete_status')->select();
      $parentid =  collection($parentid)->toArray();
      if($parentid) {
        $parentid =  array_column($parentid,'parentid');
        $parentid_2 =  $model::where('id','in',implode(',', $parentid))->field('parentid,delete_status')->select();
        $parentid_2 =  collection($parentid_2)->toArray();
        if($parentid_2){
          $parentid_2 =  array_column($parentid_2,'parentid');
          $parentid_3 =  $model::where('id','in',implode(',', $parentid_2))->field('parentid,delete_status')->select();
          $parentid_3 =  collection($parentid_3)->toArray();
          if($parentid_3) $parentid_3 =  array_column($parentid_3,'parentid');
        
       }
      }
       $imfp = array_merge(array_merge(array_merge(explode(',', $department),$parentid),$parentid_2),$parentid_3);
      if($dept = array_intersect(GetBaseInfo('Dept'),$imfp)){
            $dept_list = $model::where('id','in',implode(',', $dept))->select();
            if($dept_list){
               $dept_list = collection($dept_list)->toArray();
            }else{
              return false;
            }
       }else{
          return false;
       }
       //目前默认第一个
       if($type == 1){
        return $dept_list[0]['id'];
      }else{
        return $dept_list;
      }
    }
}
if (!function_exists('check_DepartmentChild')) {
  /*
  * 判断所属公司旗下所有部门
  * @param array  username   用户信息
  * @param array $type 返回类型 1 返回数组  2 返回字符串
  * @param array $save 保存信息
  */
    function check_DepartmentChild($department = null,$type = 1){
      $model = new \app\admin\model\AuthDepartment;
      $childid = $childid_2 = $childid_3 = [];
      $childid =  $model::where('parentid','in',$department)->field('id,delete_status')->select();
      $childid =  collection($childid)->toArray();
      if($childid){ 
        $childid =  array_column($childid,'id');
        $childid_2 =  $model::where('parentid','in',implode(',', $childid))->field('id,delete_status')->select();
        $childid_2 =  collection($childid_2)->toArray();
        if($childid_2) { 
            $childid_2 =  array_column($childid_2,'id');
            $childid_3 =  $model::where('parentid','in',implode(',', $childid_2))->field('id,delete_status')->select();
            $childid_3 =  collection($childid_3)->toArray();
            $childid_3 =  array_column($childid_3,'id');
         }
      }
      $dept = array_merge(array_merge(array_merge(explode(',', $department),$childid),$childid_2),$childid_3);
      if($type == 1){
        return $dept;
      }else{
       return implode(',', $dept);
      }
      
      
    }
}
if (!function_exists('db_tf2020')) {
    function db_tf2020($sql = ''){
        $mysql_conf = array(
            'host'    => '42.96.177.38:3306', 
            'db'      => 'tf2020', 
            'db_user' => 'wangmeng', 
            'db_pwd'  => 'wangmeng', 
            );
         
        $mysqli = @new mysqli($mysql_conf['host'], $mysql_conf['db_user'], $mysql_conf['db_pwd']);
        if ($mysqli->connect_errno) {
            die("could not connect to the database:\n" . $mysqli->connect_error);//诊断连接错误
        }
        $mysqli->query("set names 'utf8';");//编码转化
        $select_db = $mysqli->select_db($mysql_conf['db']);
        if (!$select_db) {
            die("could not connect to the db:\n" .  $mysqli->error);
        }
        $res = $mysqli->query($sql);
        if (!$res) {
            die("sql error:\n" . $mysqli->error);
        }
        $mysqli->close();
        return $res;
    }
}
if (!function_exists('sendexcelArray')) {
    function sendexcelArray($type = 1){
        $arr = [
                 '序号' => [
                    'key'=>'mynum',
                    'role'=>3,
                    'width'=>7,
                    'type'=>1,
                ],    
                 '姓名' => [
                    'key'=>'name',
                    'role'=>3,
                    'width'=>10,
                    'type'=>1,
                ],       
                '联系方式' => [
                    'key'=>'tel',
                    'role'=>3,
                    'width'=>20,
                    'type'=>1,
                ], 
                '学校名称' => [
                    'key'=>'school',
                    'role'=>3,
                    'width'=>30,
                    'type'=>1,
                ],       
                '所教年级' => [
                    'key'=>'grade',
                    'role'=>3,
                    'width'=>10,
                    'type'=>1,
                ],               
            ];
        return $arr;
    }
}
if (!function_exists('excelToArraySend')) {
   /** 
    *   方法名 :   excelToArraySend 
    *   @date   :    2019/8/2
    *   @author :    gzy 
    */    
    function excelToArraySend($filePath,$book = [],$type = '',$status){  
           $fieldArr = sendexcelArray($type);
           $nianji = [
                '一年级'=>'1',
                '二年级'=>'2',
                '三年级'=>'3',
                '四年级'=>'4',
                '五年级'=>'5',
                '六年级'=>'6',
            ];
       
          // if($type == 1)   return true;
           //print_r($fieldArr);die;
           $PHPReader = new \PHPExcel_Reader_Excel2007();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_Excel5();
                if (!$PHPReader->canRead($filePath)) {
                    $PHPReader = new \PHPExcel_Reader_CSV();
                    if (!$PHPReader->canRead($filePath)) {
                        $this->error(__('Unknown data format'));
                    }
                }
            }
            $PHPExcel = $PHPReader->load($filePath); //加载文件
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            if($allRow <= 1) return ['msg'=>'表格数据为空','status'=>1,'info'=>['file'=>$filePath,'type'=>$type,'send_publish'=>\think\Session::get('admin')['userid']]];
            if($allRow > 201)  return ['msg'=>'表格数据不能超过200条','status'=>1,'info'=>['file'=>$filePath,'type'=>$type,'send_publish'=>\think\Session::get('admin')['userid']]];
            // $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
            $maxColumnNumber = 6;
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                   $fields[] = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                }
            }
          
            $info = [];
            $info_no = [];
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $additional = [];
                $values = [];
                for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $row1 = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]['key']] = $v;
                    }
                }
                if(!isset($row['tel'])) continue;
                switch ($type) {
                    case 1:
                        $model =  new \app\admin\model\from\Teacher;
                        break;            
                     case 2:
                        $model = new \app\admin\model\from\Family;
                        break;           
                     case 3:
                        $model = new \app\admin\model\from\Promote;
                        break;
                    default:
                        return ['msg'=>'模型错误','status'=>1,'info'=>['file'=>$filePath,'type'=>$type,'send_publish'=>\think\Session::get('admin')['userid']]];
                        break;
                }

                if($row && is_telephone($row['tel'])){
                    // $model = model(GetTableModel(Sample_arr()[$type]['model']));
                     $row1 = $model->where('tel', '=', $row['tel'])->field('id,tel,message_status,message_num,receive')->find();
                     if(!$row1){
                          //去除导入新增
                         // continue;
                          // $row['grade'] = isset($nianji[$row['grade']])?$nianji[$row['grade']]:2;
                          // $row['source'] = 'excel导入';
                          // $result = $model->allowField(true)->save($row);
                          // if($result){
                          //     $row1['id'] = $model->id;
                          //     $row1['tel'] = $row['tel'];
                          //     $row1['message_status'] = 1;
                          //     $row1['message_num'] = 0;
                          //     $row1['receive'] = 1;
                          // }
                          $info_no[$row['tel']] = $row;
                     }else{
                          if($row1['receive'] == 2 || ($status == 1 && $row1['message_status'] == 2)){ 
                              unset($row,$row1,$model);
                                continue;
                          }
                         $info[$row1['tel']] = $row1;
                      }
                     //发放信息
                     unset($row,$row1,$model);
                 }
            }
             $no_url = '';
            if(!empty($info_no)){
                 $generate = ExcelSendAll($info_no);
                 if ($generate) {
                    $objWriter = PHPExcel_IOFactory::createWriter($generate, 'Excel2007');
                     //设置路径目录信息
                    $url = ROOT_PATH . 'public/uploads/sample/'.date("Ymd").'/'.'导入失败-'.time().'.xlsx';  
                    $dir_name = dirname($url);
                  //目录不存在就创建
                    if(!file_exists($dir_name)) {
                        //iconv防止中文名乱码
                       $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
                    }
                     $excelName = "uploads/sample/".date("Ymd")."/导入失败-".time().".xlsx";
                     $objWriter->save($excelName);
                     $no_url  = ''.request()->domain().'/'.$excelName.'';
                  }
                  if(!$no_url) return ['msg'=>'参数错误','status'=>1,'info'=>['file'=>$filePath,'type'=>$type,'send_publish'=>\think\Session::get('admin')['userid']]];
             }
             //测试
            // $result_dat = ['count'=>count($info_no),'ok_count'=>count($info)];
            // $result_dat['count_total'] = count($info_no)+count($info);
            // $result_dat['no_url'] = $no_url;
            // return $result_dat;
            $info = collection($info)->toArray();
       
            if(!empty($info)){ 
                $book['no_url'] = $no_url;
                $result_dat = send_message($type,$book,$info); 
                //$result_dat = send_ali_message($type,$book,$info); 
                if(!is_array($result_dat)) return ['msg'=>'发送短信失败','status'=>1,'info'=>['file'=>$filePath,'type'=>$type,'send_publish'=>\think\Session::get('admin')['userid']]];
                $result_dat['count_total'] = count($info_no)+count($info);
                $result_dat['no_url'] = $no_url;
                return  ['msg'=>'发送成功','status'=>0,'info'=>$result_dat];
               
            }
           return ['msg'=>'此类型没有此表格的数据<br>或已经发送过短信','status'=>1,'info'=>['file'=>$filePath,'type'=>$type,'send_publish'=>\think\Session::get('admin')['userid']]];
    }
}
if (!function_exists('ExcelSendAll')) {
    /**
     * 导出数据 
     * @return array
     * @author gzy
     * @time 2019年8月15日 13:35:21
     */
    function ExcelSendAll($date = []){
        if(empty($date)) return [];
        $excel = new PHPExcel();
        $total = [];
        $a = 0;
        $excel->getProperties()
            ->setCreator("gzy")
            ->setLastModifiedBy("gzy")
            ->setTitle('导入失败表')
            ->setSubject("导入失败表");
       //从第几行开始
       $line = 1;
       $styleArray = array(
             'font' => array(
                    'size'  => 10,
                    'name'  => 'Verdana'
             ),
              'borders' => array(
                    'allborders' => array( //设置全部边框
                        'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
                    ),

                ),
       );
        $worksheet = $excel->setActiveSheetIndex($a);
        $sss = 0;
        foreach(sendexcelArray() as $kk=>$vv){
            $worksheet->setCellValueByColumnAndRow($sss, $line,$kk);
            $excel->getActiveSheet()-> getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($sss))->setWidth($vv['width']);
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $sss++;
        }
        $worksheet->setTitle('导入失败表');
        $mynum = 1;//序号
        foreach ($date as $index => $item) {
                    $line++;
                    $sss = 0;
                    foreach(sendexcelArray() as $kk=>$vv){
                        if($vv['key'] == 'mynum'){
                            $worksheet->setCellValueByColumnAndRow($sss, $line, $mynum);
                        }else{
                            $worksheet->setCellValueByColumnAndRow($sss, $line, $item[$vv['key']]);
                        }
                        $worksheet->getStyleByColumnAndRow($sss,$line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                        $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
                        $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                        //$worksheet->getColumnDimension($sss)->setWidth(50);;
                        $sss++;
                    }
                $mynum++;
            }
        //print_R($total);die;
        $excel->createSheet();
        unset($worksheet);
        if($mynum>1){
            //删除空的sheet
            $sheetIndex = $excel->getIndex($excel->getSheetByName('Worksheet')); 
            $excel->removeSheetByIndex($sheetIndex);
            return $excel;
        }else{
            return [];
        }
    }
}
if (!function_exists('is_telephone')) {

  function is_telephone ($phone){
        if(preg_match("/^1[3456789]\d{9}$/", $phone))
        {
            return true;
        }
        return false;
   }
}

if (!function_exists('send_message')) {

     /*发送短信*/
    function send_message($type = 0,$book = [],$data = [],$catalog = 'send_log'){
       if(!$type)  return $type;
       $info = [];
       $i = 0;
       $info_write = [];
       $client = new \SoapClient('http://api.sms.hsyid.com:8088/XDTWebService.asmx?wsdl');
         foreach ($data as $key => $value) {
             $aryPara = [
                'user'=>'hdyjsys',
                'pwd'=>'hdyjsys323',
                'mobiles'=>$value['tel'],
                'contents'=> send_template($type,$book,$value)
            ];
           
            $response = $client->SendMessage($aryPara);
            $result = xmlToArray($response->SendMessageResult);
            //测试用 $result = ['result'=>0];
            if($result['result'] == 0){
                switch ($type) {
                    case 33:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        $info_write[$key]['ok'] = $value;
                        $info_write[$key]['ok']['id'] =   $info[$i]['id'] = $value['id'];
                        $info_write[$key]['ok']['message_status'] = $info[$i]['message_status'] = 2;
                        $info_write[$key]['ok']['message_num'] = $info[$i]['message_num'] = $value['message_num']+1;
                        $info_write[$key]['ok']['message_time'] = $info[$i]['message_time'] = time();
                        $info_write[$key]['ok']['result'] = $result;
                     break;
                    default:
                        $info_write[$key]['ok'] = $value;
                        $info_write[$key]['ok']['id'] =  $value['id'];
                        $info_write[$key]['ok']['message_status'] =  2;
                        $info_write[$key]['ok']['message_time']= time();
                        $info_write[$key]['ok']['result'] = $result;
                        break;
                }
              $i++;
            }else{
                $info_write[$key]['no'] = $value;
                $info_write[$key]['no']['result'] = $result;
            }
            unset($result,$value);
        }
        $write_arr = ['type'=>$type,'book'=>$book,'count'=>count($data),'ok_count'=>$i,'send_publish'=>\think\Session::get('admin')['userid']];
        if(!empty($info) && $type != 34 && $type != 35) model(GetTableModel(Sample_arr()[$type]['model']))->saveAll($info);
        write_log($write_arr,$info_write,1,$catalog);
        return ['count'=>count($data),'ok_count'=>$i];
    }
}
if (!function_exists('send_ali_message')) {
/*
* 阿里短信
* @param int $template 场景 1领书 2验证码
* @return boolean|int
*/
    function send_ali_message($type = 0,$book = [],$data = [],$template = 1)
    {
        if(!$type)  return $type;
        $send_sms = new \app\admin\library\AliyunSendSms(); //实例化阿里云短信类
        switch ($template) {
            case 1:
                $send_sms::$templateCode = 'SMS_173252106';
                break;
            case 2:
                $send_sms::$templateCode = 'SMS_168725684';
                break;
            default:
                return true;
                break;
        }
       $info = ['phone'=>[],'sign'=>[],'template'=>[]];
       $i = 0;
       $info_write = [];
         foreach ($data as $key => $value) {
            $info['phone'][$i] = $value['tel'];
            $info['sign'][$i] = '宏达一甲';
            $info['template'][$i] = $book;
            $info['template'][$i]['url'] =  passport_encrypt($value['id']).'___'.passport_encrypt($type);
            unset($value);
           $i++;
        }
        if($i == 1){
            $res = $send_sms::sendSms($info);
             echo "单个发送短信(sendSms)接口返回的结果:\n"; 
        }else{
          $res = $send_sms::sendBatchSms($info);
           echo "批量发送短信(sendBatchSms)接口返回的结果:\n";
        }
         print_R($res);die;
     
        $write_arr = ['type'=>$type,'book'=>$book,'count'=>count($data),'ok_count'=>$i,'send_publish'=>\think\Session::get('admin')['userid']];
        if(!empty($info)) model(GetTableModel(Sample_arr()[$type]['model']))->saveAll($info);
        write_log($write_arr,$info_write);
        return ['count'=>count($data),'ok_count'=>$i];
    }
}
if (!function_exists('write_log')) {
    function write_log($arr = [],$result = '',$type = 1,$catalog = 'send_log'){ 
        \think\Log::init([
            'type'  =>  'File',
            'path'  =>  ROOT_PATH . 'runtime/logs/'.$catalog.'/',
             // 日志记录级别
            'level' => [],
        ]);
        \think\Log::record('信息','error');
        $years = date('Ym');
        //设置路径目录信息
        $url = ROOT_PATH . 'runtime/logs/'.$catalog.'/'.$years.'/'.date('Ymd').'_request_log.log';  
        $dir_name=dirname($url);
      //目录不存在就创建
         if(!file_exists($dir_name)) {
            //iconv防止中文名乱码
           $res = mkdir(iconv("UTF-8", "GBK", $dir_name),0777,true);
        }
        $fp = fopen($url,"a");//打开文件资源通道 不存在则自动创建
        switch ($type) {
             case 1:
              $record = var_export($arr,true)."\r\n\r\n".var_export($result,true)."\r\n\r\n执行结束：".date("Y-m-d H:i:s")."\r\n\r\n".'---------------------------------------------------------------------------------'."\r\n\r\n";
               break;
             case 2:
              $record = "\r\n\r\n".'---------------------------------------------------------------------------------'."\r\n\r\n开始执行：".date("Y-m-d H:i:s")."\r\n\r\n";
               break;
            case 3:
               $record = var_export($arr,true)."\r\n\r\n执行失败：".date("Y-m-d H:i:s")."\r\n\r\n".'---------------------------------------------------------------------------------'."\r\n\r\n";
               break;
            case 4:
               $record = var_export($arr,true)."\r\n\r\n发送时间：".date("Y-m-d H:i:s")."\r\n\r\n".'---------------------------------------------------------------------------------'."\r\n\r\n";
               break;
             default:
               # code...
               break;
           } 
        fwrite($fp,$record);//写入文件      
        fclose($fp);//关闭资源通道
    }
}
if (!function_exists('send_template')) {

     /*发送短信*/
    function send_template($type = 0,$book = [],$data = []){
   
        switch ($type) {
            case 33:
                $template = "领书提醒：《小学生绘本课堂·素材书》现已正式出版上市，请已经预约登记的家长于".$book['date']."至".$book['address']."领取，家长需凭组委会官方短信通知链接中的二维码领取".$book['book_name']."。数量有限，先到先得，领完为止，领取活动仅限".$book['only_date']."，过期请到书店自选。乘车路线：".$book['car']."。咨询电话：".$book['tel_phone']."。未预约的家长，可以点击如下链接进行预约tmall.fc62.com/form_tuijian.html，凭收到的短信通知到上面书店领取。【宏达一甲】";
                break; 
            case 1:
            case 2:
            case 3:
            $lock_tel = passport_encrypt($data['id']).'___'.passport_encrypt($type);
            $template ="领书通知：《小学生绘本课堂·素材书》现已正式出版上市，请已经预约登记的家长于".$book['date']."至".$book['address']."领取，家长可凭以下链接oa.fc62.com/S/".$lock_tel." 中二维码领取".$book['book_name']."。数量有限，先到先得，领完为止，领取活动仅限".$book['only_date']."，过期请到书店自选。乘车路线：".$book['car']."。咨询电话：".$book['tel_phone']."。【宏达一甲】";
                break;
            case 4:
            $lock_tel = passport_encrypt($data['id']).'___'.passport_encrypt($type);
            $template ="测试领书通知：《小学生绘本课堂·素材书》现已正式出版上市，请已经预约登记的家长于".$book['date']."至".$book['address']."领取，家长可凭以下链接oa.fc62.com/S/".$lock_tel." 中二维码领取".$book['book_name']."。数量有限，先到先得，领完为止，领取活动仅限".$book['only_date']."，过期请到书店自选。乘车路线：".$book['car']."。咨询电话：".$book['tel_phone']."。宏达技术循环测试拦截【宏达一甲】";
               
                break;
            case 35:
                $template = "尊敬的".$book['parent_name']."，您好，您已经成功签订了《提分宝典》服务保障合同，合同编号为：".$book['contract_no']."，请妥善保管，切勿丢失或遗忘。【宏达一甲】";
                break; 
            default:
               $template = '';
                break;
        }
        return $template;

    }

}
if (!function_exists('Sample_arr')) {
   function Sample_arr(){ 
     
      $arr = [
            '1'=>['model'=>'Teacher'],
            '2'=>['model'=>'Family'],
            '3'=>['model'=>'Promote'],
            '34'=>['model'=>'Contract'],
        ];
        return $arr;
    } 
}
if (!function_exists('passport_encrypt')) {
   function passport_encrypt($txt, $key = 'oa.hdyj.com'){ 
       $result = '';
        for($i=0; $i<strlen($txt); $i++) {
            $char = substr($txt, $i, 1);
            $keychar = substr($key, ($i % strlen($key))-1, 1);
            $char = chr(ord($char)+ord($keychar));
            $result.=$char;
        }
        return base64_encode($result);
    } 
}
if (!function_exists('passport_decrypt')) {
    function passport_decrypt($txt, $key = 'oa.hdyj.com'){ 
      $result = '';
        $txt = base64_decode($txt);
        for($i=0; $i<strlen($txt); $i++) {
            $char = substr($txt, $i, 1);
            $keychar = substr($key, ($i % strlen($key))-1, 1);
            $char = chr(ord($char)-ord($keychar));
            $result.=$char;
        }
        return $result;
    }                       
}

if (!function_exists('xmlToArray')) {
   function xmlToArray($xml,$isfile=false){
      //禁止引用外部xml实体
      libxml_disable_entity_loader(true);
      if($isfile){
        if(!file_exists($xml)) return false;
        $xmlstr = file_get_contents($xml);
      }else{
        $xmlstr = $xml;
      }
      $result= json_decode(json_encode(simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
      return $result;
    }
}

/*库存数量*/
function stock_num($shopid,$cid){
    if ($shopid <=0 || $cid <=0 )return false;
    $shopid = $shopid;
    $pDb = new \app\admin\model\Preproduct();
    $shop = $pDb->where(array('id'=>$shopid))->find();
    $bcp = $shop['bcp'];
    $nums=0;

    if (empty($bcp))return $nums;
    $models = new \app\admin\model\Stock;

    $list = $pDb ->where("id in ($bcp)")
        ->select();

    $arr = collection($list)->toArray();
    $data=array();
    $min=array();//最小值
    foreach ($arr as $k=>$v){
        $sto = $models->where(array("cid"=>$cid,"shopid"=>$v['id']))->find();
        if ($sto){
            $num = $sto['num'];
        }else{
            $num = 0;
        }

        $min[]=$num;
    }
    $sto_min = min($min);
    return $sto_min;

}
function add_stock($cid,$shopid,$num,$userid)
{
    if ($cid < 0 || !$shopid || $num < 0)return false;
    $preDb = new \app\admin\model\Preproduct();
    $stDb = new \app\admin\model\Stock();
    $inDb = new \app\admin\model\house\In();
    //查询半成品
    $info = $preDb->find($shopid);
    $bcp = explode(',',$info['bcp']);
    $order_id = $inDb->getOrderId();
    $type=3;
    if (!$bcp)return false;
    foreach ($bcp as $d){
        $starr = $stDb->where(array('cid'=>$cid,'shopid'=>$d))->find();
        if ($starr){
            //修改
            $stDb->where(array('cid'=>$cid,'shopid'=>$d))->setInc('num', $num); ;

        }else{
            $stDb->insert(array(
                'cid'=>$cid,
                'shopid'=>$d,
                'num'=>$num

            ));
            //添加
        }
        //库存表操作
    }
    $inDb->insert(array(
        "order_id"=>$order_id,
        'type'=>$type,
        'shopid'=>$shopid,
        'num'=>$num,
        'cid'=>$cid,
        'pur_id'=>0,
        'inputtime'=>time(),
        'publisher'=>$userid,
        'mark'=>"退货",
        'bcp'=>$info['bcp'],

    ));

    if (Think\Db::name('stock_data')->where(array("cid"=>$cid,"shopid"=>$shopid,"bcp"=>$info['bcp']))->find()){
        Think\Db::name('stock_data')->where(array("cid"=>$cid,"shopid"=>$shopid,"bcp"=>$info['bcp']))->setInc('num', $num); ;

    }else{
        Think\Db::name('stock_data')->insert(array(
            'shopid'=>$shopid,
            'num'=>$num,
            'bcp'=>$info['bcp'],
            'cid'=>$cid
        ));
    }
    return true;

}
/*郜振宇要货入库函数*/
function gzy_reduce_stock($cid,$pruArr,$userid){

    if ($cid < 2 || !$pruArr)return false;
    $preDb = new \app\admin\model\Preproduct();
    $stDb = new \app\admin\model\Stock();
    $outDb = new \app\admin\model\Houseout();
    $pruArr=array_filter($pruArr,function ($v){
        if ($v['num'] > 0){
            return $v;
        }
    });

    if (!$pruArr)return false;
    $shopArr=array();//所有半成品id，压榨入库
    //检车当前库是否存在
    foreach ($pruArr as $k=>$v){
        $shopid = $v["id"];
        $num=$v['num'];
        $info = $preDb->where(array("id"=>$shopid))->field('id,type,bcp')->find();
        if ($info['type']==2){//
            $bcp = $info['bcp'];
            $pruArr[$k]['type']=2;
            $pruArr[$k]['bcp']=$bcp;

            $bcp = explode(",",$bcp);
            foreach ($bcp as $d){
                if (!array_key_exists($d,$shopArr)){
                    $shopArr["a_".$d]=$num;
                }else{
                    $shopArr["a_".$d]+=$num;
                }
            }
        }else{
            $pruArr[$k]['type']=1;
            if (!array_key_exists($shopid,$shopArr)){
                $shopArr["a_".$shopid]=$num;
            }else{
                $shopArr["a_".$shopid]+=$num;
            }
        }
    }

    $tempStatus=[];
    //检测库存
    foreach ($shopArr as $key=>$val){
        $key=intval(substr($key,2));

        $info = $stDb->where(array('cid'=>1,"shopid"=>$key))->find();
        if (!$info){
            $tempStatus=array("status"=>0,"id"=>$key);
            break;
        }
        if ($info['num'] < $val){
            $tempStatus=array("status"=>0,"id"=>$key);
            break;
        }
    }
    if ($tempStatus)return $tempStatus;

    \think\Db::startTrans();
    //减总部库存
    $order_id = $outDb->getOrderId();
    foreach ($shopArr as $key=>$value){
        $key=intval(substr($key,2));
         $stDb->where(array('cid'=>1,"shopid"=>$key))->setDec("num",$value);
            $outDb->insert(array(
                "order_id"=>$order_id,
                'type'=>4,
                'shopid'=>$key,
                'num'=>$value,
                'cid'=>1,
                'pur_id'=>0,
                'inputtime'=>time(),
                'publisher'=>$userid,
                'mark'=>"分公司要货",
                "bcp"=>''

            ));

    }
    $inArr=[];
    $inDb = new \app\admin\model\house\In();
    $in_id=$inDb->getOrderId();
    foreach ($pruArr as $k=>$v){
        $inArr=array(
            "order_id"=>$in_id,
            'type'=>2,
            'shopid'=>$v['id'],
            'num'=>$v['num'],
            'cid'=>$cid,
            'pur_id'=>0,
            'inputtime'=>time(),
            'publisher'=>$userid,
            'mark'=>"要货入库",
        );
        if($v['type']==2){//成品
            if ($stDb->where(array("shopid"=>$v['id'],"cid"=>$cid,"type"=>2))->find()) {
                $stDb->where(array("shopid" => $v['id'], "cid" => $cid,"type"=>2))->setInc("num", $v['num']);
            }else{
                $stDb->insert(array(
                    "cid"=>$cid,
                    "shopid"=>$v['id'],
                    "num"=>$v['num'],
                    "type"=>2
                ));
            }
           $inArr['bcp']=$v['bcp'];
        }else{
            if ($stDb->where(array("shopid"=>$v['id'],"cid"=>$cid,"type"=>1))->find()) {
                $stDb->where(array("shopid" => $v['id'], "cid" => $cid,"type"=>1))->setInc("num", $v['num']);
            }else{
                $stDb->insert(array(
                    "cid"=>$cid,
                    "shopid"=>$v['id'],
                    "num"=>$v['num'],
                    "type"=>1
                ));
            }
            $inArr['bcp']='';
        }
        $inDb->insert($inArr);
    }
    \think\Db::commit();

    return array("status"=>1,"order_id"=>$in_id);

}
/*gzy 发货单作废*/
function gzy_fahuodan_zuofei($cid,$pruArr,$userid){
    if ($cid < 0 || !$pruArr)return false;
    $preDb = new \app\admin\model\Preproduct();
    $stDb = new \app\admin\model\Stock();
    $outDb = new \app\admin\model\Houseout();
    $shopArr=array();//所有半成品id，压榨入库
    foreach ($pruArr as $v){
        $shopid = $v["id"];
        $num=$v['num'];
        $info = $preDb->where(array("id"=>$shopid))->field('id,type,bcp')->find();
        if ($info['type']==2){//
            $bcp = $info['bcp'];
            $bcp = explode(",",$bcp);
            foreach ($bcp as $d){
                if (!array_key_exists($d,$shopArr)){
                    $shopArr["a_".$d]=$num;
                }else{
                    $shopArr["a_".$d]+=$num;
                }
            }
        }else{
            if (!array_key_exists($shopid,$shopArr)){
                $shopArr["a_".$shopid]=$num;
            }else{
                $shopArr["a_".$shopid]+=$num;

            }
        }

    }

    //foreach循环结束
    //检测库存
    if ($cid==1)return false;
    $tempStatus=[];

    foreach ($shopArr as $key=>$val){
        $key=intval(substr($key,2));

        $info = $stDb->where(array('cid'=>$cid,"shopid"=>$key))->find();
        if (!$info){
            $tempStatus=array("status"=>0,"id"=>$key);
            break;
        }
        if ($info['num'] < $val){
            $tempStatus=array("status"=>0,"id"=>$key);
            break;
        }

    }
    if ($tempStatus)return $tempStatus;
    $order_id = $outDb->getOrderId();
    $inDb = new \app\admin\model\house\In();
    $in_id=$inDb->getOrderId();
    foreach ($shopArr as $sid=>$va){
        $sid=intval(substr($sid,2));
        $stDb->where(array("cid"=>$cid,"shopid"=>$sid))->setDec("num",$va);//分公司减库存
        //分公司加库存
        if ($stDb->where(array("cid"=>1,"shopid"=>$sid))->find()){
            $stDb->where(array("cid"=>1,"shopid"=>$sid))->setInc("num",$va);//总公司加库存
        }else{

            $ids=$stDb->insert(
                array(
                    "cid"=>$cid,
                    "shopid"=>$sid,
                    'num'=>$va
                )
            );
        }
        $outDb->insert(array(
            "order_id"=>$order_id,
            'type'=>7,
            'shopid'=>$sid,
            'num'=>$va,
            'cid'=>$cid,
            'pur_id'=>0,
            'inputtime'=>time(),
            'publisher'=>$userid,
            'mark'=>"发货单作废",
            "bcp"=>''

        ));
        $inDb->insert(array(
            "order_id"=>$in_id,
            'type'=>3,
            'shopid'=>$sid,
            'num'=>$va,
            'cid'=>1,
            'pur_id'=>0,
            'inputtime'=>time(),
            'publisher'=>$userid,
            'mark'=>"发货单作废",
            "bcp"=>''

        ));

    }
    return array("status"=>1,"order_id"=>$in_id);
}
/*发货单作废*/
function fahuodan_zuofei($pruArr,$userid){
    $preDb = new \app\admin\model\Preproduct();
    $stDb = new \app\admin\model\Stock();
    $shopArr=array();//所有半成品id，压榨入库
    foreach ($pruArr as $v){
        $shopid = $v["id"];
        $num=$v['num'];
        $info = $preDb->where(array("id"=>$shopid))->field('id,type,bcp')->find();
        if ($info['type']==2){//
            $bcp = $info['bcp'];
            $bcp = explode(",",$bcp);
            foreach ($bcp as $d){
                if (!array_key_exists($d,$shopArr)){
                    $shopArr["a_".$d]=$num;
                }else{
                    $shopArr["a_".$d]+=$num;
                }
            }
        }else{
            if (!array_key_exists($shopid,$shopArr)){
                $shopArr["a_".$shopid]=$num;
            }else{
                $shopArr["a_".$shopid]+=$num;

            }
        }

    }
    $inDb = new \app\admin\model\house\In();
    $in_id=$inDb->getOrderId();
    foreach ($shopArr as $sid=>$va){
        $sid=intval(substr($sid,2));
        //分公司加库存
       $stDb->where(array("cid"=>1,"shopid"=>$sid))->setInc("num",$va);//总部加库存
        $inDb->insert(array(
            "order_id"=>$in_id,
            'type'=>3,
            'shopid'=>$sid,
            'num'=>$va,
            'cid'=>1,
            'pur_id'=>0,
            'inputtime'=>time(),
            'publisher'=>$userid,
            'mark'=>"发货单作废",
            "bcp"=>''

        ));

    }
    return array("status"=>1,"order_id"=>$in_id);

}
/*杨柳函数*/
function reduce_stock($cid,$pruArr,$userid){
    if ($cid < 0 || !$pruArr)return false;
    $preDb = new \app\admin\model\Preproduct();
    $stDb = new \app\admin\model\Stock();
    $outDb = new \app\admin\model\Houseout();
    $shopArr=array();//所有半成品id，压榨入库



    foreach ($pruArr as $v){
           $shopid = $v["id"];
           $num=$v['num'];
           $info = $preDb->where(array("id"=>$shopid))->field('id,type,bcp')->find();
           if ($info['type']==2){//
                $bcp = $info['bcp'];
                $bcp = explode(",",$bcp);
                foreach ($bcp as $d){
                    if (!array_key_exists($d,$shopArr)){
                        $shopArr["a_".$d]=$num;
                    }else{
                        $shopArr["a_".$d]+=$num;
                    }
                }
           }else{
               if (!array_key_exists($shopid,$shopArr)){
                   $shopArr["a_".$shopid]=$num;
               }else{
                   $shopArr["a_".$shopid]+=$num;

               }
           }

    }

    //foreach循环结束
   //检测库存
    $tempStatus=[];

    foreach ($shopArr as $key=>$val){
       $key=intval(substr($key,2));

        $info = $stDb->where(array('cid'=>$cid,"shopid"=>$key))->find();
        if (!$info){
            $tempStatus=array("status"=>0,"id"=>$key);
            break;
        }
        if ($info['num'] < $val){
            $tempStatus=array("status"=>0,"id"=>$key);
            break;
        }
    }
    if ($tempStatus)return $tempStatus;
    $order_id = $outDb->getOrderId();
    foreach ($shopArr as $sid=>$va){
        $sid=intval(substr($sid,2));

        $stDb->where(array("cid"=>$cid,"shopid"=>$sid))->setDec("num",$va);//减库存
        $outDb->insert(array(
            "order_id"=>$order_id,
            'type'=>5,
            'shopid'=>$sid,
            'num'=>$va,
            'cid'=>$cid,
            'pur_id'=>0,
            'inputtime'=>time(),
            'publisher'=>$userid,
            'mark'=>"发货",
            "bcp"=>''

        ));

    }
    return array("status"=>1,"order_id"=>$order_id);

}
if (!function_exists('random')) {


    function random($length, $numeric = 0)
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }
}
if (!function_exists('random_code')) {


    function random_code($length, $chars = '01234567893216549870') {
        $hash = '';
        $max = strlen($chars) - 1;
        for($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }
}


//表格处理函数，对于跨列的处理
if (!function_exists('cols')) {
    //列数，当前循环，总数组
    function cols($index, $i, $arr)
    {
        if (!array_key_exists($index, $arr)) return false;
        $key = array_keys($arr[$index]);
        if (in_array($i, $key)) {
            return $arr[$index][$i];
        }
        return false;
    }
}
if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name)
            return $name;
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }

}

if (!function_exists('array_sort')) {

    /*
     * 数组排序
     * @param array $arr 数组
     * @param  string $keys 指定key
     * @param string $type 顺序desc 倒序asc
     */
    function array_sort($arr, $keys, $type = 'desc')
    {
        $key_value = $new_array = array();
        foreach ($arr as $k => $v) {
            $key_value[$k] = $v[$keys];
        }
        if ($type == 'asc') {
            asort($key_value);
        } else {
            arsort($key_value);
        }
        reset($key_value);
        foreach ($key_value as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
        return $new_array;
    }

}



if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++)
            $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }

}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }

}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }

}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $url = preg_match("/^https?:\/\/(.*)/i", $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
            if (is_bool($domain)) {
                $public = \think\Config::get('view_replace_str.__PUBLIC__');
                $url = rtrim($public, '/') . $url;
                if (!preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
                    $url = request()->domain() . $url;
                }
            } else {
                $url = $domain . $url;
            }
        }
        return $url;
    }

}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === FALSE) {
                return FALSE;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return TRUE;
        } elseif (!is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) {
            return FALSE;
        }
        fclose($fp);
        return TRUE;
    }

}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname))
            return false;
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }

}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }

}

if (!function_exists('mb_ucfirst')) {

    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }

}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields)
            return $items;
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }

}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, TRUE);
        }
    }

}
/****************公共函数**************/
if (!function_exists('AdminAuth')) {

	 /**
     * 生成编号
	 * @author gzy
     */
    function GenerateNumber($id = NULL) {
		if(empty($id)) return '';
		$where = "`extract_week` = '".$id."'";
		$info = model(GetTableModel('Books'))->field('number')->where($where)->order('id desc')->find();
		if(empty($info)) return 1;
		return $info['number']+1;
	//	print_R($info['number']);die;
	//	return date('YmdHis') . str_pad(mt_rand(1, 99), 3, '0', STR_PAD_LEFT);
    }
}
if (!function_exists('AdminAuth')) {

	 /**
     * 判断是否有模块权限
     * @param  int    $function  路径  如 finance/extract/week/index 代表的就是 http://bdoa.fc62.com/admin/finance/extract/week/index
     * @return array
	 * @author gzy
	 * @date   2018年8月29日 13:00:00
     */
    function AdminAuth($function = '') {
		if(empty($function)) return false;
		$auth = \app\admin\library\Auth::instance();
		$data = $auth->check($function);
        return $data;
    }
}
if (!function_exists('GetUpdateApiData')) {
	 /**
     * 获取/更改 api数据
     * @param  int    $type  默认值 Dept=部门
     * @param  array  $array 自定义数据 
     * @param  string $action 动作 
     * @return array
	 * @author gzy
	 * @date   2018年8月12日 13:30:00
     */
    function GetUpdateApiData($type = 0,$array = [],$action = '') {
        $data = [];
		switch ($type) {
			//获取所有部门数据
			 case 'Dept':
				 $array['action'] = $action;
				 $data = \fast\Http::post(request()->domain()."/api/data/dept", $array);
				//$data = file_get_contents(request()->domain()."/api/data/dept");
                break;
			//用户操作
			 case 'User':
				 $array['action'] = $action;
				 $data = \fast\Http::post(request()->domain()."/api/data/user", $array);
                break;
            default:
                break;
        }
        return $data;
    }
}
if (!function_exists('GetErrorLang')) {
	 /**
     * 微信状态码 错误
     * @param  int    $error  状态码
     * @return string
	 * @author gzy
	 * @date   2018年8月12日 13:30:00
     */
    function GetErrorLang($error,$result = []) {
        $data = [
				'-1'=>'模块不存在/系统繁忙',
				'-2'=>'参数缺失',
				'-3'=>'微信链接有问题啦,请刷新后重试',
				'-4'=>'您没有操作的权限',
				'-5'=>'您的数据没有同步，请联系管理员',
				'-6'=>'未登录',
        '48002'=>'API接口无权限调用',
				'45024'=>'帐号数量超过上限',
				'40066'=>'不合法的部门列表',
				'60003'=>'部门ID不存在',
				'60004'=>'父部门不存在',
				'60005'=>'部门下存在成员',
				'60006'=>'部门下存在子部门',
				'60007'=>'不允许删除根部门',
				'60008'=>'部门已存在',
				'60009'=>'部门名称含有非法字符',
				'60010'=>'部门存在循环关系',
				'60011'=>'指定的成员/部门/标签参数无权限',
				'60102'=>'userid已存在微信,请更新最新数据',
				'60103'=>'手机号不合法',
				'60104'=>'手机号已存在,请更新最新数据',
				'60105'=>'邮箱不合法',
				'60106'=>'邮箱已存在,请更新最新数据',
				'60123'=>'无效的部门id',
				'60124'=>'无效的父部门id',
                '60125'=>'缺少参数code',
				];
		    if(isset($data[$error])){
          return $data[$error];
        }else{
          if($result){
            return $result['errmsg'];
          }else{
            return '操作失败 01';
          }
        }
        
    }
}

if (!function_exists('ObjectArray')) {
	 /**
     * 将对象转换为数组 
     * @param  int    $data  对象
     * @return string
	 * @author gzy
	 * @date   2018年8月15日 13:30:00
     */
  
	function ObjectArray($data) {
		  $_arr = is_object($data) ? get_object_vars($data) :$data;
		  $arr = [];
		  foreach ($_arr as $key=>$val){
			   $val = (is_array($val) || is_object($val)) ? ObjectArray($val):$val;
			   $arr[$key] = $val;
		  }
		  return $arr;
	}

}
if (!function_exists('TableListSqlQuery')) {
	 /**
     * 通过不同表名获取列表内容 调用基础数据用
     * @param  string  tabel    表名 model
     * @param  int		id       数据id 
     * @param  string  fieldName 自定义查找name 默认id 
     * @return string
	 * @author gzy
	 * @date   2018年8月25日 15:30:00
     */
    function TableListSqlQuery($type = NUll,$where = '1 = 1',$field = NULL,$table = NULL,$order = NULL) {
			switch ($type) {
				//日记账 天数
				  case 'Books':
					$sql = "SELECT
							books.extract_week,books.day,
								sum(CASE books.pay_type WHEN 1 THEN price END) as income,
								sum(CASE  WHEN books.pay_type = 2 and cost.type = 1 THEN price END) as expenditure
							FROM
								hdyj_finance_extract_books as books LEFT JOIN hdyj_base_cost as cost ON books.cost_id = cost.id
							where ".$where." 
							GROUP BY books.DAY ORDER BY books.day asc";
					break;
				//日记账详情
				  case 'Books_view':
					$sql = "SELECT
								books.*
							FROM
								hdyj_finance_extract_books as books LEFT JOIN hdyj_base_cost as cost ON books.cost_id = cost.id
							where ".$where." and  (cost_id in (select id from hdyj_base_cost where `type` = 1) or `pay_type` = 1)";
					break;
				  case 'Admin':
					$sql = "SELECT
						".$field.",
						(select group_concat(b.group_id) from hdyj_auth_group_access as b where admin.userid = b.userid) as position
						FROM
							hdyj_admin as admin
						where ".$where." ";
					break;
			      case 'User':
					$sql = "SELECT
						".$field." FROM
							hdyj_admin as admin
						where ".$where." ";
					break;
				  case 'Field':
					$sql = "SELECT
						".$field." FROM
							".$table."
						where ".$where." ".$order." ";
					break;
				//统计信息
				  case 'Analysis':
					$sql = "SELECT season.id,season_time,address,province,city,area,lecturer_id,subject_id,people_num,coming_num,school.gift_books,book_num,book_price,school.id AS sid,school.type AS type,season.outreach_extract,
							school.school_id AS school_id,
							(SELECT group_concat(b.userid, '||', b.proportion) FROM hdyj_finance_extract_school_data AS b WHERE school.id = b.extract_school AND b.type = 1) AS userid_data,
							(SELECT group_concat(b.price, '||', b.num  order by b.price desc) FROM hdyj_finance_extract_school_data AS b WHERE school.id = b.extract_school AND b.type = 2) AS price_data,
							(SELECT sum(b.price * b.num) FROM hdyj_finance_extract_school_data AS b WHERE school.id = b.extract_school AND b.type = 2) AS price_total,
						    (SELECT sum(b.num) FROM hdyj_finance_extract_school_data AS b WHERE school.id = b.extract_school AND b.type = 2) AS price_num
						FROM hdyj_finance_extract_season AS season LEFT JOIN hdyj_finance_extract_school AS school ON season.id = school.season_id
						WHERE ".$where." ".$order."";
					break;
					//统计日记账
				  case 'AnalysisBooks':
					$sql = "SELECT cost.name,cost.id,cost.type,
							(SELECT sum(books.price) FROM hdyj_finance_extract_books AS books WHERE ".$where." AND cost.id = books.cost_id AND books.pay_type = 2)AS price_total FROM hdyj_base_cost AS cost WHERE cost.delete_status = 1 ORDER BY cost.type,cost.weigh desc ";
					break;
				  //总公司财务填写
				  case 'AnalysisBooks2':
					$sql = "SELECT cost.name,cost.id,cost.type,
							(SELECT sum(books.price) FROM hdyj_finance_extract_books AS books WHERE ".$where." AND cost.id = books.cost_id AND books.pay_type = 2) AS price_total,(SELECT books.id FROM hdyj_finance_extract_books AS books WHERE ".$where." AND cost.id = books.cost_id AND books.pay_type = 2) AS books_id FROM hdyj_base_cost AS cost WHERE cost.delete_status = 1 and cost.type = 2 ORDER BY cost.type,cost.weigh desc ";
					break;
				 //财务填写总数
				  case 'AnalysisBooksTotal':
					$sql = "SELECT cost.type,sum(books.price) AS price_total FROM hdyj_base_cost AS cost LEFT JOIN hdyj_finance_extract_books AS books ON cost.id = books.cost_id WHERE cost.delete_status = 1 AND books.pay_type = 2 and books.cost_id not in ('23','20') and ".$where." GROUP BY cost.type";
					break;
				 //一轮书统计信息
				  case 'Round_analysis':
					$sql = "SELECT season.id,season_time,address,province,city,area,lecturer_id,subject_id,sales_type,pricing_type,pricing_price,sales_price,pricing_num,round_num,round.`desc`,round.`data` FROM hdyj_finance_extract_season AS season LEFT JOIN hdyj_finance_extract_round AS round ON season.id = round.season_id WHERE ".$where." ORDER BY season.id,round.weigh asc";
					break;
				//用户信息
				  case 'UserInfo':
					$sql = "SELECT
							info.id,info.userid,info.status_week,info.contract_price,info.unit_price,shares_price,shares_proportion,info.weigh,admin.username,admin.department,
						  (select group_concat(b.group_id) from hdyj_auth_group_access as b where admin.userid = b.userid) as position
						FROM
							hdyj_admin_info AS info
						LEFT JOIN hdyj_admin AS admin ON info.userid = admin.userid
						WHERE
							".$where." ORDER BY info.weigh asc";
					break;
				//用户周提成总价钱
				  case 'UserWeek':
					$sql = "SELECT
							sum(u.week_total) as week_total,
							sum(u.no_ticket_total) as no_ticket_total,
							sum(u.admission_fee) as admission_fee,
							sum(u.week_total_round) as books_total 
							FROM
								hdyj_finance_extract_week as w LEFT JOIN hdyj_finance_extract_user as u on w.id = u.extract_week
							where
							".$where." ";
					  break;
				//查询分公司周折合
				  case 'DeptWeek':
					$sql = "SELECT
							dept.id,w.department,dept.parentid,dept.name,w.into_36,w.into_29
							FROM
								hdyj_finance_extract_week as w LEFT JOIN hdyj_auth_department as dept on w.department  = dept.id
							where ".$where."";
					break;
				//月版税合计
				  case 'WeekTaxTotal':
					$sql = "SELECT
								userid,
								sum(admission_fee) as admission_fee,
								sum(week_total) as week_total,
								sum(tax_total) as tax_total,
								sum(tax_owe) as tax_owe,
								sum(no_ticket_total) as no_ticket_total,
								sum(no_ticket_noowe) as no_ticket_noowe,
								sum(no_ticket_owe) as no_ticket_owe,
								sum(real_hair) as real_hair,
								sum(point_total) as point_total,
								sum(books_total) as books_total,
								sum(contract_total) as contract_total,
								sum(shares_total) as shares_total,
								".$field."
							FROM
								hdyj_finance_extract_info
							WHERE 
								".$where."
							GROUP BY
								userid";          $sql = "SELECT u.*, g.weigh,(SELECT group_concat(name order by weigh desc) AS position_text FROM hdyj_auth_group WHERE find_in_set(id,u.position) > 0 LIMIT 0,1) AS position_text,(SELECT username FROM hdyj_admin WHERE `userid` = u.userid LIMIT 0,1 ) AS username_text FROM hdyj_finance_extract_user AS u left join hdyj_auth_group AS g ON u.position = g.id WHERE ".$where." ORDER BY g.weigh DESC";

					break;
					//周提成用户信息
				  case 'UserExtract':
					$sql = "SELECT u.*, c.weigh,(SELECT group_concat(name order by weigh desc) AS position_text FROM hdyj_auth_group WHERE find_in_set(id,u.position) > 0 and id in (".GetBaseInfo('FPosition').") LIMIT 0,1) AS position_text,g.username as username_text,g.thumb_avatar,g.avatar FROM  (hdyj_finance_extract_user AS u inner join hdyj_admin AS g ON u.userid = g.userid) LEFT join hdyj_auth_group as c ON u.position=c.id WHERE ".$where." ORDER BY c.weigh DESC";
					break;
				//会销表数据-提分
				  case 'SalesAnalysis':
					$sql = "SELECT season.id,season_time,address,province,city,area,lecturer_id,subject_id,sdata.price,sum(sdata.num) as num,sum(price) as price_total FROM hdyj_finance_extract_season AS season LEFT JOIN hdyj_finance_extract_school AS school ON season.id = school.season_id LEFT JOIN hdyj_finance_extract_school_data as sdata ON school.id = sdata.extract_school WHERE ".$where." and sdata.type = 2 and sdata.num > 0 GROUP BY season.id,sdata.price";
					break;
				//会销表数据-一轮书
				  case 'SalesRound_analysis':
					$sql = "SELECT season.id,season_time,address,province,city,area,lecturer_id,subject_id,round.pricing_type, round.sales_price as price,round.pricing_num as num FROM hdyj_finance_extract_season AS season LEFT JOIN hdyj_finance_extract_round AS round ON season.id = round.season_id   WHERE ".$where." ORDER BY round.weigh DESC";
					break;
          //纸质版试卷申领
          case 'Management':
          $sql = "SELECT ".$field." FROM hdyj_management WHERE ".$where." and gift = 1 and (locate('绘本课堂',version) > 0 OR locate('绘本课堂',goods) > 0 ) AND (locate('下单',version) = 0 and locate('下单',goods) = 0 ) AND (locate('下', version) > 0 OR locate('下',goods) > 0 ) ";
          break;
				 default:
					$sql = '';
					break;
			}
			if(empty($sql)) return [];
			return \think\Db::query($sql);
    }
}
if (!function_exists('TableList')) {
	 /**
     * 通过不同表名获取列表内容 调用基础数据用
     * @param  string  tabel    表名 model
     * @param  int		id       数据id 
     * @param  string  fieldName 自定义查找name 默认id 
     * @return array
	 * @author gzy
	 * @date   2018年8月25日 15:30:00
     */
    function TableList($table = '',$value = '1',$fieldName = 'delete_status',$additional = [],$sort = NULL,$order = NULL,$type = 1) {
  		if(empty($value)||empty($table)) return [];
  		$model = model(GetTableModel($table));
      if($type == 1){
  	 	 $arr = [];
  		  $arr[$fieldName] = $value;
  	   if(!empty($additional)) $arr = array_merge($arr,$additional);
      }else{
        $arr = $fieldName.' = '.$value;
        $arr .= $additional;
     }
  		if(!$sort){
  			$info = $model->where($arr)->select();
  		}else{
  			$info = $model->where($arr)->order($sort, $order)->select();
  		}
  		//获取sql
  		//print_R($model->getLastSql());die;
  		if(empty($info)) return [];
  		return collection($info)->toArray();
    }
}
if (!function_exists('TableField')) {
	 /**
     * 通过不同表名获取不同内容
     * @param  string  tabel    表名 model
     * @param  string  field    返回字段 默认name
     * @param  int	   value       数据值 
     * @param  string  fieldName 自定义查找name 默认id 
	 * @param  arr     additional  附加值
     * @return string
	 * @author gzy
	 * @date   2018年8月12日 15:30:00
     */
    function TableField($table = '',$field = 'name',$value = '',$fieldName = 'id',$additional = [],$type = 1) {
			if(empty($value)||empty($table)) return '';
			$model = model(GetTableModel($table));
			$arr = [];
			$arr[$fieldName] = $value;
			if(!empty($additional)) $arr = array_merge($arr,$additional);
			$row = $model->get($arr);
			//获取sql
			//print_R($model->getLastSql());
			if(empty($row)) return '';
            if($type == 1){
			         return $row[$field];
             }else{
			         return $row;
            }
        }
}
if (!function_exists('GetExplode')) {
	 /**
     * 公共处理字段分割信息 职位信息/部门信息
     * @param  array  info  数据信息 其他跟TableField一样
     * @param  string  table  表名 model
     * @return string
	 * @author gzy
	 * @date   2018年8月25日 15:00:00
     */
    function GetExplode($info = [],$table = '',$field= 'name',$fieldName = 'id') {
			if(empty($info)) return '';
			$data = '';
			foreach($info as $key=>$val){
				$value = TableField($table,$field,$val,$fieldName);
				if(!empty($value)) $data .= $value.',';
			}
			return trim($data,",");
    }
}
if (!function_exists('GetTableModel')) {
	 /**
     * 根据表名获取 model 信息
     * @param  int    $table  默认值 Position=职位 AuthGroup=权限组=部门
     * @return array
	 * @author gzy
	 * @date   2018年8月25日 16:30:00
     */
    function GetTableModel($table) {
		switch ($table) {
			 case 'Position':
			 case 'Cost':
			 case 'Subject':
       case 'Lecturer':
       case 'School_B':
			 case 'Book':
       if($table == 'School_B') $table = 'School';
				$model  = 'admin/base/'.$table;
				break;
			 case 'WechatUser':
			 case 'AuthGroup':
			 case 'Area':
			 case 'DataSchool':
			 case 'Admin':
			 case 'AuthDepartment':
       case 'AuthRule':
       case 'Wageslist':
       case 'Wages':
       case 'Management':
			 case 'Admininfo':
				if($table == 'DataSchool') $table = 'School';
				$model = 'admin/'.$table;
                break;
			 case 'Week':
			 case 'School':
			 case 'Books':
			 case 'Season':
			 case 'User':
			 case 'Info':
			 case 'Month':
       case 'Venue_sales':
       case 'Task':
			 case 'Note':
				if($table == 'Venue_sales') $table = 'Round';
				$model = 'admin/finance/extract/'.$table;
                break;
       case 'School_data':
         $model = 'admin/finance/extract/school/Data';
              break;
        case 'Teacher':
             case 'Family':
			 case 'Promote':
				$model = 'admin/from/'.$table;
                break;
       case 'WeixinUser':
        $model = 'admin/weixin/'.$table;
                break; 
        case 'Special':
        $model = 'admin/serial/'.$table;
            break; 
        case 'LiveUser':
        $model = 'common/User';
                break;
        case 'Volume':
        case 'VolumeSubject':
        case 'VolumeSchool':
        case 'VolumeSubjectData':
        if($table == 'VolumeSchool') $table = 'School';
        $model = 'admin/ques/'.$table;
                break;    
        case 'Contract':
        $model = 'admin/shop/'.$table;
                break;        
            default:
				$model = '';
                break;
        }
        return $model;
    }
}
if (!function_exists('GenerateDate')) {
	 /**
     * 生成指定时间
     * @param  int    $type  类型
     * @param  int    $strtotime  是否时间戳1否2是
     * @return array
	 * @author gzy
	 * @date   2018年8月28日 14:30:00
     */
    function GenerateDate($type,$strtotime = 1) {
		$time = [];
		switch ($type) {
			//上周
			 case 'LastWeek':
				$time['start_time'] = date('Y-m-d', strtotime('last week Monday', time()));
				$time['end_time'] = date('Y-m-d', strtotime('last week sunday', time()));
				break;
			//本周
			 case 'Week':
				$time['start_time'] = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
				$time['end_time'] = date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600));
                break;
            default:
                break;
        }
		if($strtotime == 2){
			if(isset($time['start_time'])) $time['start_time'] = strtotime($time['start_time']);
			if(isset($time['end_time'])) $time['end_time'] = strtotime($time['end_time']);
		}
        return $time;
    }
}
if (!function_exists('GetYearWeek')) {
	 /**
     * 获取当年的自然周 不跨年
     * @param  int    $year  年 
     * @return array
	 * @author gzy
	 * @date   2018年9月21日 14:30:00
     */
    function GetYearWeek($year = NULL) {
		if(empty($year)) return [];
		$year_start = $year.'-01-01';
		$year_end = $year.'-12-31';
		$startday = strtotime($year_start);
		$a = 1;
		$num = 53;
		if(intval(date('N',$startday)) != '1'){
			$startday = strtotime('next monday',$startday);//获取年第一周的日期
			$num = 52;
		}
		$year_mondy = date('Y-m-d',$startday);
		for($i=1; $i<=$num; $i++){
			$j = $i-$a;
			$start_date = date('Y-m-d',strtotime("$year_mondy $j week "));
			$end_day = date('Y-m-d',strtotime("$start_date +6 day "));
			$week_array[$i] = [$start_date,$end_day];
		}
		return $week_array;
	}
}
 /**
     * 获取当年的自然周 可跨年
     * @param  int    $year  年 
     * @return array
   * @author gzy
   * @date   2018年9月21日 14:30:00
    
    function GetYearWeek($year = NULL) {
    if(empty($year)) return [];
    $year_start = $year.'-01-01';
    $year_end = $year.'-12-31';
    $startday = strtotime($year_start);
    $a = 1;
    $num = 52;
    if(intval(date('N',$startday)) != '1'){
      $last_start_day = strtotime('last monday',$startday);//获取上一年最后一周
      $last_year_mondy = date('Y-m-d',$last_start_day);
      $startday = strtotime('next monday',$startday);//获取年第一周的日期
      $a = 2;
      $num = 53;
    }
    $year_mondy = date('Y-m-d',$startday);
    for($i=1; $i<=$num; $i++){
      $j = $i-$a;
      if(isset($last_year_mondy)){
        $start_date = date('Y-m-d',strtotime("$last_year_mondy 0 week "));
        $end_day = date('Y-m-d',strtotime("$start_date +6 day "));
        unset($last_year_mondy);
      }else{
        $start_date = date('Y-m-d',strtotime("$year_mondy $j week "));
        $end_day = date('Y-m-d',strtotime("$start_date +6 day "));
      }
      $week_array[$i] = [$start_date,$end_day];
    }
    return $week_array;
  } */
  if (!function_exists('GetYearWeekOne')) {
   /**
     * 获取时间是第几周
     * @param  int    $year  年 
     * @param  int    $time  日期 y-m-d 
     * @return array
   * @author gzy
   * @date   2018年9月21日 14:30:00
     */
    function GetYearWeekOne($year = NULL,$time) {
    if(empty($year)) return [];
    $year_start = $year.'-01-01';
    $year_end = $year.'-12-31';
    $startday = strtotime($year_start);
    $a = 1;
    $num = 53;
    if(intval(date('N',$startday)) != '1'){
      $startday = strtotime('next monday',$startday);//获取年第一周的日期
      $num = 52;
    }
    $year_mondy = date('Y-m-d',$startday);
    for($i=1; $i<=$num; $i++){
      $j = $i-$a;
      $start_date = date('Y-m-d',strtotime("$year_mondy $j week "));
      $end_day = date('Y-m-d',strtotime("$start_date +6 day "));
      if($time == $start_date){
        return $i;
      }
      $week_array[$i] = [$start_date,$end_day];
    }
  }
	
}
if (!function_exists('ValueExists')) {
	/**
	 * 检查str是否存在于strs
	 *
	 * @param $str
	 * @param $strs
	 * @param $pars
	 * @author gzy
	 * @time 2018年9月10日 13:00:10
	 */
	function ValueExists($str, $strs = '', $pars = ','){
		if (empty($strs)) return FALSE;
		$strs = explode($pars, $strs);
		return is_array($str) ? array_intersect($str, $strs) : in_array($str, $strs);
	}
}
if (!function_exists('GetRows')) {
	/**
	 * 管理权限 
	 * @return array
	 * @author gzy
	 * @time 2018年9月10日 10:00:21
	 */
	function GetRows(){
		if(AdminAuth('see/all')){
			return 1;
		}
		if(AdminAuth('see/dept')){
			return 2;
		}
		if(AdminAuth('see/one')){
			return 3;
		}
	}
}
if (!function_exists('ArrayAdd')) {
	/**
	 * 一维数组合并 并求和 
	 * @return array
	 * @author gzy
	 * @time 2018年9月14日 15:00:00
	 */
	function ArrayAdd($a = [],$b = []){
		 $arr = array_intersect_key($a,$b);
		 foreach($b as $key=>$value){
			  if(!array_key_exists($key,$a)){
					 $a[$key] = $value;
			  }
		 }
		 foreach($arr as $key=>$value){
			   $a[$key] = $a[$key] + $b[$key];
		 }
		 return $a;
	}
}
if (!function_exists('GetCheck')) {
	 /**
     * 检查权限
     * @param       $name   string|array    需要验证的规则列表,支持逗号分隔的权限规则或索引数组
     * @param       $ids 用户权限id 逗号分隔
     * @return bool  通过验证返回true;失败返回false
     */
    function GetCheck($name, $ids = NUll){
		if(empty($ids)) return false;
        // 获取用户需要验证的所有有效规则列表
        $rulelist = GetRuleList($ids);
        if (in_array('*', $rulelist))return true;
        if (is_string($name)){
            $name = strtolower($name);
            if (strpos($name, ',') !== false){
                $name = explode(',', $name);
            }else{
                $name = [$name];
            }
        }
        $list = []; //保存验证通过的规则名
        foreach ($rulelist as $rule){   
			if (in_array($rule, $name)){
				$list[] = $rule;
			}
            
        }
        if (!empty($list)){
            return true;
        }
        return false;
    }
}
if (!function_exists('GetRuleList')) {
	/**
     * 获得权限规则列表 - 提成相关权限
     * @param integer $group_ids 用户权限id 逗号分隔
     * @return array
	 * @time 2018年9月15日 19:00:00
     */
    function GetRuleList($group_ids = NUll){
		if(empty($group_ids)) return [];
		$group_ids = explode(',',$group_ids);
		
        $where_group['id'] = ['in', $group_ids];
        //读取用户所属用户组
        $groups = \think\Db::name('auth_group')->where($where_group)->field('id,id as group_id,pid,name,rules')->select();

        $ids = []; //保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g){
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $rulelist = []; //
        $ids = array_unique($ids);
		$where = [];
	    if (!in_array('*', $ids)){
            $where['id'] = ['in', $ids];
        }else{
            $rulelist[] = "*";
        }

		if(empty($where)) return $rulelist;
		//读取用户组所有权限规则
        $rules = \think\Db::name('auth_rule')->where($where)->field('id,pid,condition,icon,name,title,ismenu')->select();
        //循环规则，判断结果。
        if (in_array('*', $ids))
        {
            $rulelist[] = "*";
        }
        foreach ($rules as $rule){
              //只要存在就记录
             $rulelist[$rule['id']] = strtolower($rule['name']);
           
        }  
        return array_unique($rulelist);
    }
}
if (!function_exists('Rounding')) {
	/**
     * 四舍五入
     * @param num 数值
     * @return float
	 * @time 2018年9月15日 19:00:00
     */
    function Rounding($num = 0,$decimal = 2){
		if(!$num) return 0;
		return number_format($num, $decimal, '.', '');
    }
}

/****************财务管理 提成相关**************/

if (!function_exists('GetAnalysisAll')) {
	/**
	 * 获取周提成总数据  提分
	 * @return array
	 * @author gzy
	 * @time 2018年9月10日 10:00:21
	 */
	function GetAnalysisAll($type = NULL,$id = NULL){
		if(empty($id) || empty($type)) return [];
		$arr = [
				'total'=>[
					//扣除成本后销售总额 - 周
					'sales_priceTotal'=>0,
					//销售总额 - 周
					'price_total'=>0,
					//销售总数量
					'price_num'=>0,
					//来人数
					'people_numTotal'=>0,
					//总数
					'coming_numTotal'=>0,
					//赠书总数
					'gift_booksTotal'=>0,
					//手边题本总价格 - 周
					'book_priceTotal'=>0,
					//手边题本总数量 - 周
					'book_numTotal'=>0,
					//手边题本单科成本 - 周
					'book_price'=>0,
					//场次数量  - 周
					'season_num'=>0,
					//2986折合 - 周  不扣成本
					'into_cost_29'=>0,
					//2986折合 - 周
					'into_29'=>0,
					//3686折合- 周 
					'into_36'=>0,
					//外联单场提成标准
					'OutreachExtract'=>0,
					//外联提成 - 周
					'OutreachExtractPirce'=>0,
					//单套折合 - 周
					'into_one'=>0,
					//单套折合29 - 周
					'into_one_29'=>0,

					//费用表 信息
					//费用合计 - 周 
					'books_price'=>0,
					//销售利润 - 周 
					'sales_price'=>0,
					//单场费用 - 周 
					'season_onePrice'=>0,
					//单套费用 - 周 
					'book_onePrice'=>0,
					//管理提成费用 - 周 
					'ManageExtractPrice'=>0,
					//管理提成标准 - 周 
					'ManageExtract'=>0,
				],
				//费用合计
				'bookstotal'=>[],
				'all'=>[],
				 //销售价格数量信息 - 周
				'sales_price'=>[],
				 //提成信息 - 周
				'extract'=>[
						//管理提成 
						'manage'=>[
							'price'=>0,
							'his'=>0,
							'deputyhis'=>0
						 ],
						//会务提成 
						'meeting'=>0,
						//客服提成
						'service'=>0,
						//财务提成
						'finance'=>0,
						//股份提成
						'shares'=>0,
					],

			 ];
		//费用合计
		$arr['bookstotal'] = array_column(TableListSqlQuery($type.'BooksTotal','books.`extract_week` = '.$id.''),null,'type');
		//没有判断是否为空
		$arr['total']['books_price'] = $arr['bookstotal']? Rounding(($arr['bookstotal'][1]['price_total']??0) + ($arr['bookstotal'][2]['price_total']??0)):0;

		$season = TableListSqlQuery($type,'season.`extract_week` = '.$id.' or school.`extract_week` = '.$id.'',null,null,"order by type asc");

		if(empty($season)) return $arr; 
		$key_arr = array('season_time','address','province','city','area','lecturer_id','subject_id');
		$Standard = GetBaseInfo('OutreachExtract')['Standard'];
		$Standard10 = GetBaseInfo('OutreachExtract')['Standard10'];
		$Standard10_lt = GetBaseInfo('OutreachExtract')['Standard10_lt'];
		$Standard_lt = GetBaseInfo('OutreachExtract')['Standard_lt'];
		$Standard_egt = GetBaseInfo('OutreachExtract')['Standard_egt'];
		$SalesPrice_1 = GetBaseInfo('SalesPrice')['SalesPrice_1'];
		$SalesPrice_2 = GetBaseInfo('SalesPrice')['SalesPrice_2'];
		$StandardPrice = GetBaseInfo('ManageExtract')['StandardPrice'];
		$StandardPrice_lt = GetBaseInfo('ManageExtract')['StandardPrice_lt'];
		$StandardPrice_egt = GetBaseInfo('ManageExtract')['StandardPrice_egt'];
		$EachSet = GetBaseInfo('Public')['EachSet'];
		$MeetingPrice = GetBaseInfo('Public')['MeetingPrice'];
		$ServicePrice = GetBaseInfo('Public')['ServicePrice'];
		$FinancePrice = GetBaseInfo('Public')['FinancePrice'];
		
		foreach($season as $key=>$val){
			foreach($key_arr as $a => $b){
			   $arr['all'][$val['id']][$b] = $val[$b];
			   unset($val[$b]);
			}
            $arr['all'][$val['id']]['id'] = $val['id'];
            $arr['all'][$val['id']]['type'] = $val['type'];
            $arr['all'][$val['id']]['outreach_extract'] = $val['outreach_extract'];
			//总人数 - 场次
			if(!isset($arr['all'][$val['id']]['people_numTotal'])) $arr['all'][$val['id']]['people_numTotal'] = 0;
            $arr['all'][$val['id']]['people_numTotal'] += $val['people_num']?:0;
			
			//来人总人数 - 场次
			if(!isset($arr['all'][$val['id']]['coming_numTotal'])) $arr['all'][$val['id']]['coming_numTotal'] = 0;
			$arr['all'][$val['id']]['coming_numTotal'] += $val['coming_num']?:0;
			//来人总人数 - 场次
			if(!isset($arr['all'][$val['id']]['gift_booksTotal'])) $arr['all'][$val['id']]['gift_booksTotal'] = 0;
			$arr['all'][$val['id']]['gift_booksTotal'] += $val['gift_books']?:0;
			//手边题本总价格 - 学校
			$val['book_priceTotal'] = Rounding($val['book_num'] * $val['book_price']);
			//手边题本总价格 - 场次
			if(!isset($arr['all'][$val['id']]['book_priceTotal'])) $arr['all'][$val['id']]['book_priceTotal'] = 0;
			$arr['all'][$val['id']]['book_priceTotal'] += $val['book_priceTotal']?:0;
			//手边题本数量 - 场次
			if(!isset($arr['all'][$val['id']]['book_numTotal'])) $arr['all'][$val['id']]['book_numTotal'] = 0;
			$arr['all'][$val['id']]['book_numTotal'] += $val['book_num']?:0;
			//手边题本单科成本 - 场次
			if(!isset($arr['all'][$val['id']]['book_price'])) $arr['all'][$val['id']]['book_price'] = 0;
			$arr['all'][$val['id']]['book_price'] += $val['book_price']?:0;

			//扣除成本后销售总额 - 学校
			$val['sales_priceTotal'] = Rounding($val['price_total'] - $val['book_priceTotal']);
			//扣除成本后销售总额 -场次 按场次金额合计
			if(!isset($arr['all'][$val['id']]['sales_priceTotal'])) $arr['all'][$val['id']]['sales_priceTotal'] = 0;
			$arr['all'][$val['id']]['sales_priceTotal'] += $val['sales_priceTotal']?:0;
			//销售总额 -场次
			if(!isset($arr['all'][$val['id']]['price_total'])) $arr['all'][$val['id']]['price_total'] = 0;
			$arr['all'][$val['id']]['price_total'] += $val['price_total']?:0;
			//销售数量 -场次
			if(!isset($arr['all'][$val['id']]['price_num'])) $arr['all'][$val['id']]['price_num'] = 0;
			$arr['all'][$val['id']]['price_num'] += $val['price_num']?:0;
			//单套折合 - 学校
			$val['into_one'] = $val['sales_priceTotal'] ? Rounding($val['sales_priceTotal']/$SalesPrice_2):0;
			//单套折合 -场次
			if(!isset($arr['all'][$val['id']]['into_one'])) $arr['all'][$val['id']]['into_one'] = 0;
			$arr['all'][$val['id']]['into_one'] += $val['into_one']?:0;
			//单套折合29 - 学校
			$val['into_one_29'] = $val['sales_priceTotal'] ? Rounding($val['sales_priceTotal']/$SalesPrice_1):0;
			//单套折合29 -场次
			if(!isset($arr['all'][$val['id']]['into_one_29'])) $arr['all'][$val['id']]['into_one_29'] = 0;
			$arr['all'][$val['id']]['into_one_29'] += $val['into_one_29']?:0;
			//销售价格数量信息 - 学校
			$price_info = explode(',',$val['price_data']);
			$val['price_info'] = [];
			foreach($price_info as $k=>$v){
				$info = explode('||',$v);
				if(isset($info[1])){
					$val['price_info'][$info[0]] = $info[1] ?? 0;
					unset($info,$v);
				}
			}
			unset($price_info);
			$arr['sales_price'] = ArrayAdd($arr['sales_price'], $val['price_info']);
			
			
			//学校信息
			$arr['all'][$val['id']]['school'][$val['sid'] ?: 0] = $val['sid'] ? $val:[];
			unset($val);
		}
	
		//print_R($arr);die;
		foreach($arr['all'] as $kk=>&$vv){
			//2986折合
			$vv['into_29'] = $vv['sales_priceTotal'] ? Rounding($vv['sales_priceTotal']/$SalesPrice_1):0;
			$vv['into_cost_29'] = $vv['price_total'] ? Rounding($vv['price_total']/$SalesPrice_1):0;
			//3686折合
			$vv['into_36'] = $vv['sales_priceTotal'] ? Rounding($vv['sales_priceTotal']/$SalesPrice_2):0;
            //判断追加、退货
             if($vv['type'] == 1){
    			//外联单场提成标准
    			switch (true) {
    			 case abs($vv['into_29']) <= $Standard10 :
    				//$OutreachExtract = $Standard_egt;
    			    $vv['OutreachExtract'] = $Standard10_lt;
    				break;
    			 case abs($vv['into_29']) > $Standard10 && abs($vv['into_29']) < $Standard &&  abs($vv['into_29']) > 0 :
    			 	$vv['OutreachExtract'] = Rounding(abs($vv['into_29']) * $Standard_lt);
    				break;
    			 case abs($vv['into_29']) >= $Standard :
    				//$OutreachExtract = $Standard_egt;
    			    $vv['OutreachExtract'] = $Standard_egt;
    				break;
    			 default:
    				$OutreachExtract = 0;
    			    $vv['OutreachExtract'] = 0;
    				break;
    			}
            }else{
                $vv['OutreachExtract'] = $vv['outreach_extract'];
            }
		
			if(!empty($vv['school'])){
				//外联提成 - 学校
				foreach($vv['school'] as $k=>&$v){
					  if(isset($v['school_id'])){
						$v['OutreachExtract'] = 0;
						if(isset($v['into_one'])){
							$v['OutreachExtract'] =  Rounding($vv['OutreachExtract'] * $v['into_one']);
							$arr['total']['OutreachExtractPirce'] += $v['OutreachExtract']?:0;
						}
						//外联信息 - 学校
						$userid_data = explode(',',$v['userid_data']);
						$v['userid_info'] = [];
						foreach($userid_data as $ks=>$vs){
							$info = explode('||',$vs);
							if(isset($info[1])){
								$v['userid_info'][$info[0]]['name'] = TableField('Admin','username',$info[0],'userid');
								$v['userid_info'][$info[0]]['value'] = $info[1] ?? 0;
								$v['userid_info'][$info[0]]['extract'] = Rounding($info[1]? $v['OutreachExtract']*$info[1]/100:0 );
								$v['userid_info'][$info[0]]['into_one_29'] = Rounding($info[1]? $v['into_one_29']*$info[1]/100:0 );
								//外联提成信息 - 周
								if(!isset($arr['outreach_info'][$info[0]])) $arr['outreach_info'][$info[0]] = 0;
								$arr['outreach_info'][$info[0]] += $v['userid_info'][$info[0]]['extract']?:0;
								//外联折合信息 - 周
								if(!isset($arr['into_one_29'][$info[0]])) $arr['into_one_29'][$info[0]] = 0;
								$arr['into_one_29'][$info[0]] += $v['userid_info'][$info[0]]['into_one_29']?:0;
								unset($info,$vs);
							}
						}
						unset($userid_data);
						$v['school_name'] =  TableField('DataSchool','name',$v['school_id']);
					}
				}
			}
            //判断追加、退货
            if($vv['type'] == 1){
    			$arr['total']['price_num'] += $vv['price_num']?:0;
    			$arr['total']['into_one'] += $vv['into_one']?:0;
    			$arr['total']['into_one_29'] += $vv['into_one_29']?:0;
    			$arr['total']['OutreachExtract'] += $vv['OutreachExtract']?:0;
    			$arr['total']['book_price'] += $vv['book_price']?:0;
    			$arr['total']['book_numTotal'] += $vv['book_numTotal']?:0;
    			$arr['total']['people_numTotal'] += $vv['people_numTotal']?:0;
    			$arr['total']['coming_numTotal'] += $vv['coming_numTotal']?:0;
    			$arr['total']['gift_booksTotal'] += $vv['gift_booksTotal']?:0;
    			$arr['total']['sales_priceTotal'] += $vv['sales_priceTotal']?:0;
    			$arr['total']['book_priceTotal'] +=  $vv['book_priceTotal']?:0;
    			$arr['total']['price_total'] +=  $vv['price_total']?:0;

    			$arr['total']['season_num'] ++;
           }
		}
		$arr['total']['into_29'] = $arr['total']['sales_priceTotal'] ? Rounding($arr['total']['sales_priceTotal']/$SalesPrice_1):0;
		$arr['total']['into_cost_29'] = $arr['total']['price_total'] ? Rounding($arr['total']['price_total']/$SalesPrice_1):0;
		$arr['total']['into_36'] = $arr['total']['sales_priceTotal'] ? Rounding($arr['total']['sales_priceTotal']/$SalesPrice_2):0;
		//销售利润
		$arr['total']['sales_price'] = Rounding($arr['total']['sales_priceTotal'] - $arr['total']['books_price']);
		//单场费用
		$arr['total']['season_onePrice'] = $arr['total']['season_num'] ? Rounding($arr['total']['books_price'] / $arr['total']['season_num']):0;
		//单套费用
		$arr['total']['book_onePrice'] = $arr['total']['into_36'] ? Rounding($arr['total']['books_price'] / $arr['total']['into_36']):0;

		$arr['extract']['meeting'] = Rounding($arr['total']['into_36'] * $MeetingPrice);
		$arr['extract']['service'] = Rounding($arr['total']['into_36'] * $ServicePrice);
		$arr['extract']['finance'] = Rounding($arr['total']['into_36'] * $FinancePrice);

		//管理提成标准
		switch (true) {
		 case abs($arr['total']['book_onePrice']) <= $StandardPrice && abs($arr['total']['book_onePrice']) > 0:
			$ManageExtract = $StandardPrice_lt['price'];
			$arr['extract']['manage']['his'] = $ExtractHis = $StandardPrice_lt['ExtractHis'];
			$arr['extract']['manage']['deputyhis'] = $ExtractDeputyHis = $StandardPrice_lt['ExtractDeputyHis'];
			break;
		 case abs($arr['total']['book_onePrice']) > $StandardPrice :
			$ManageExtract = $StandardPrice_egt['price'];
			$arr['extract']['manage']['his'] = $ExtractHis = $StandardPrice_egt['ExtractHis'];
			$arr['extract']['manage']['deputyhis'] = $ExtractDeputyHis = $StandardPrice_egt['ExtractDeputyHis'];
			break;
		 default:
			$ManageExtract = 0;
			$ExtractHis = 0;
			$ExtractDeputyHis = 0;
			break;
		}
		foreach($arr['all'] as $kk=>&$vv){
            $vv['lecturer_name'] = TableField('Lecturer','name',$vv['lecturer_id']);
            $vv['subject_name'] = TableField('Subject','name',$vv['subject_id']);
            //判断追加、退货
            if($vv['type'] != 1) continue;
			//管理提成标准 - 场次
			if(abs($vv['into_29']) < $EachSet){
				$vv['ManageExtract'] = Rounding(abs($vv['into_29']) / $EachSet * $ManageExtract);
			}else{
				$vv['ManageExtract'] = $ManageExtract;
			}
			//管理提成金额 - 场次
			$vv['ManageExtractPrice'] = Rounding($vv['into_36'] * $vv['ManageExtract']);
		
			$arr['total']['ManageExtractPrice'] += $vv['ManageExtractPrice']?:0;
			$arr['extract']['manage']['price'] += $vv['ManageExtractPrice']?:0;
			$arr['total']['ManageExtract'] += $vv['ManageExtract']?:0;
		
		}
		
		return $arr;
	}
}

if (!function_exists('GetAnalysisBooks')) {
	/**
	 * 获取周提成总数据 
	 * @return array
	 * @author gzy
	 * @time 2018年9月10日 10:00:21
	 */
	function GetAnalysisBooks($type = NULL,$id = NULL,$true = FALSE){
		if(empty($id) || empty($type)) return [];
		$arr = TableListSqlQuery($type.'Books','books.`extract_week` = '.$id.'');
		if($true){
		   $arr = serialize($arr);
		}
		return $arr;
	}
}
if (!function_exists('GetUserExtractAll')) {
	/**
	 * 获取周用户提成
	 * @return array
	 * @author gzy
	 * @time 2018年9月15日 15:00:00
	 */
	function GetUserExtractAll($User = [],$id = NULL,$true = FALSE){
		if(empty($User)||empty($id)) return [];
		$pid = TableField('AuthRule','id','extract/index','name');
		$AuthInfo = TableList('AuthRule',$pid,'pid',[],'weigh','desc');
		$Analysis  = GetAnalysisAll('Analysis',$id);
		
		$data = [];
		$data['AuthInfo'] = $AuthInfo;
		$data['outreach_info'] = $Analysis['outreach_info']??[];
		$data['into_one_29'] = $Analysis['into_one_29']??[];
		$data['extract'] = $Analysis['extract']??[];
		//分成方式
		$data['division_method'] = TableField('Week','division_method',$id,'id');
		//无票金额 23969.30
		$data['no_ticket'] = TableField('Week','no_ticket',$id,'id');
		$data['NoTicketRate'] = GetBaseInfo('NoTicketRate');
		$info = [
			'User'=>[],
			'Total'=>[
				'week_total' => 0,
				'no_ticket_total' => 0,
				'no_ticket' => 0,
				'no_ticketPrice' => $data['no_ticket'],
			],
		];		
		//无票扣发
		if($data['no_ticket']) $info['Total']['no_ticket'] =  $data['no_ticket'] = Rounding($data['no_ticket'] * $data['NoTicketRate']['Rate'] / 100);
		//print_r($data);die;
		
		//if($data['division_method'] == 1) 
			$extract_num = [
				'outreach'=>0,
				'meeting'=>0,
				'service'=>0,
				'finance'=>0,
				'manage'=>0,
				'fmanage'=>0,
			];
	
		foreach($User as $key=>&$val){
			$val['week_total'] = 0;
			$val['into_one_29'] = 0;
			$val['no_ticket_total'] = 0;
			$val['count'] = 1;
			$val['extract'] = [];
			if(!empty($val['position'])){
				$data['position'] = $val['position'];
				$data['userid'] = $val['userid'];
				$data['proportion'] = $val['proportion'];
				$extract = GetUserExtractOne(1,$id,$data);
				if(!empty($extract)){
					$val['extract'] = $extract['extract']??[];
					$val['week_total'] = $extract['week_total'];
					$val['into_one_29'] = $extract['into_one_29'];
					$val['no_ticket_total'] = $extract['no_ticket_total'];
					//if($data['division_method'] == 1){
						if(isset($val['extract']['outreach'])|| isset($val['extract']['outreach80'])) $extract_num['outreach']++;
						if(isset($val['extract']['meeting'])) $extract_num['meeting']++;
						if(isset($val['extract']['service'])) $extract_num['service']++;
						if(isset($val['extract']['finance'])) $extract_num['finance']++;
						if(isset($val['extract']['manage'])) $extract_num['manage']++;
						if(isset($val['extract']['fmanage'])) $extract_num['fmanage']++;
					
					//}
				}
				if($val['admission_fee']){
					$val['extract']['admission']['price'] = $val['admission_fee'];
					$val['extract']['admission']['title'] = '参会费';
					$val['week_total'] += $val['admission_fee'];
				}
				$val['count'] = count($val['extract']);
			}
		
			$info['Total']['week_total'] += $val['week_total'];
			$info['Total']['no_ticket_total'] += $val['no_ticket_total'];
			
		}
		
		//判断是人均还是百分比 来计算无票金额  无票金额不用判断就平均
		//if($data['division_method'] == 1){
			foreach($User as $kk=>&$vv){
				if(!empty($vv['extract'])){
					$price = 0;
					$no_ticket_price = 0;
					//判断总经理和副总的人数并平均
					if(isset($vv['extract']['manage'])&& $extract_num['manage']){
						$price += $vv['extract']['manage']['price'] = Rounding($vv['extract']['manage']['price']/$extract_num['manage']);
						$no_ticket_price += isset($data['no_ticket']) ? Rounding($data['no_ticket']*$data['NoTicketRate']['His']/100/$extract_num['manage']):0;
					}
					if(isset($vv['extract']['fmanage']) && $extract_num['fmanage']){
						$price += $vv['extract']['fmanage']['price'] = Rounding($vv['extract']['fmanage']['price']/$extract_num['fmanage']);
						$no_ticket_price += isset($data['no_ticket']) ? Rounding($data['no_ticket']*$data['NoTicketRate']['DeputyHis']/100/$extract_num['fmanage']):0;
					}
					if(isset($vv['extract']['outreach'])  && $extract_num['outreach']){
						$no_ticket_price += isset($data['no_ticket']) ? Rounding($data['no_ticket']*$data['NoTicketRate']['Outreach']/100/$extract_num['outreach']):0;
					}
					if(isset($vv['extract']['outreach80']) && $extract_num['outreach']){
						$no_ticket_price += isset($data['no_ticket']) ? Rounding($data['no_ticket']*$data['NoTicketRate']['Outreach']/100/$extract_num['outreach']*80/100):0;
					}
					if(isset($vv['extract']['meeting']) && $extract_num['meeting']){
						$price += $vv['extract']['meeting']['price'] = Rounding($vv['extract']['meeting']['price']/$extract_num['meeting']);
						$no_ticket_price += isset($data['no_ticket']) ? Rounding($data['no_ticket']*$data['NoTicketRate']['Meeting']/100/$extract_num['meeting']):0;
					}
					if(isset($vv['extract']['service']) && $extract_num['service']){
						$price += $vv['extract']['service']['price'] = Rounding($vv['extract']['service']['price']/$extract_num['service']);
						$no_ticket_price += isset($data['no_ticket']) ? Rounding($data['no_ticket']*$data['NoTicketRate']['Service']/100/$extract_num['service']):0;
					}
					if(isset($vv['extract']['finance']) && $extract_num['finance']){
						$price += $vv['extract']['finance']['price'] = Rounding($vv['extract']['finance']['price']/$extract_num['finance']);
						$no_ticket_price += isset($data['no_ticket']) ? Rounding($data['no_ticket']*$data['NoTicketRate']['Finance']/100/$extract_num['finance']):0;
					}
					$vv['week_total'] += $price;
					$vv['no_ticket_total'] += $no_ticket_price;
					$info['Total']['week_total'] += $price;
					$info['Total']['no_ticket_total'] += $no_ticket_price;
					unset($price);
				}
				
			}
		//}
		
		$info['User'] = $User;
		
		if($true){
			foreach($info['User'] as $k=>$v){
				$extract = '';
				if(!empty($v['extract']))$extract = serialize($v['extract']);
				$info['GenerateUser'][$k] = [
					'id'=>$v['id'],
					'week_total'=>$v['week_total'],
					'into_one_29'=>$v['into_one_29'],
					'no_ticket_total'=>$v['no_ticket_total'],
					'count'=>$v['count'], 
					'extract'=>$extract,
					];
			
			 }
		}
		return $info;
	
	}
}
if (!function_exists('GetRoundAnalysisAll')) {
	/**
	 * 获取周提成总数据 一轮书
	 * @return array
	 * @author gzy
	 * @time 2018年11月9日 10:30:21
	 */
	function GetRoundAnalysisAll($type = NULL,$id = NULL){
		if(empty($id) || empty($type)) return [];
		$arr = [
				'total'=>[
					//扣除成本后销售总额 - 周
					'sales_priceTotal'=>0,
				   //销售总额 - 周
          'price_total'=>0,	
            //单科/组合总价 - 周
					'pricing_total'=>0,
				
					//单科数量/组合数量 - 周
					'pricing_num'=>0,
					//一轮书总数量/销售数量总计  - 周
					'round_num'=>0,
					
					//一轮书总成本- 周
					'round_priceTotal'=>0,
					
					//公司50  - 周
					'Company50_price'=>0,
					//公司55  - 周
					'Company55_price'=>0,
					//公司60  - 周
					'Company60_price'=>0,

					//应发版税  - 周
					'should_price'=>0,

					//2986折合 - 周
					'into_29'=>0,
					//4000折合 - 周
					'into_40'=>0,
				],
				//总信息
				'all'=>[],
				 
			 ];
	
		$season = TableListSqlQuery($type,'season.`extract_week` = '.$id.'');
		//print_r($season);die;
		if(empty($season)) return $arr; 
		$key_arr = array('season_time','address','province','city','area','lecturer_id','subject_id');
		$Sales_type = GetBaseInfo('RoundInfo')['Sales_type'];
		$StandardNum = GetBaseInfo('RoundExtract')['StandardNum'];
		$StandardNum_lt = GetBaseInfo('RoundExtract')['StandardNum_lt'];
		$StandardNum_egt = GetBaseInfo('RoundExtract')['StandardNum_egt'];
		$CompanyExtract = GetBaseInfo('CompanyExtract');

		$SalesPrice_1 = GetBaseInfo('SalesPrice')['SalesPrice_1'];
		$SalesPrice_5 = GetBaseInfo('SalesPrice')['SalesPrice_5'];
		$grade = !empty($id) ? TableField('Week','grade',$id) : 3;
         //分三档提成
        switch ($grade) {
         case 1:
            $should_price = 'Company50_price';
            break;
         case 2:
           $should_price = 'Company55_price';
            break;   
        case 3:
            $should_price = 'Company60_price';
            break;
         default:
            $should_price = 'Company60_price';
            break;
        }
        
		foreach($season as $key=>$val){
			foreach($key_arr as $a => $b){
			   $arr['all'][$val['id']][$b] = $val[$b];
			   unset($val[$b]);
			}
            //成本
            $val['round_price'] = $val['sales_type'] ? $Sales_type[$val['sales_type']]['cost'] : 0;
            //一轮书总成本 - 场次
            $val['round_priceTotal'] = Rounding($val['round_num'] * $val['round_price']);
            //一轮书总成本 - 场次
            if(!isset($arr['all'][$val['id']]['round_num'])) $arr['all'][$val['id']]['round_num'] = 0;
            $arr['all'][$val['id']]['round_num'] += $val['round_num']?:0;
            if($val['pricing_type'] == 2){
                $val['data'] = $val['data'] ? ObjectArray(json_decode($val['data'])):[];
                $val['pricing_total'] = $val['data'] ? Rounding(array_sum(array_map(function($vss){return $vss['pricing_price']*$vss['round_num'];}, $val['data']))):0;
                $val['data_info'] = '';
                if(!empty($val['data'])){
                    foreach ($val['data'] as $vssk) {
                       $val['data_info'] .= '<tr >
                            <td style="text-align: center; vertical-align: middle; ">'.$vssk['pricing_price'].'</td>
                            <td style="text-align: center; vertical-align: middle; ">'.$vssk['round_num'].'</td>
                            <td style="text-align: center; vertical-align: middle; ">'.Rounding($vssk['pricing_price']*$vssk['round_num']).'</td>
                        </tr>';
                    }
                }
                
               
            }elseif($val['pricing_type'] == 1){
                //单科/组合 总价 - 场次
                 $val['pricing_total'] = Rounding($val['pricing_price'] * $val['round_num']);
            }else{
                 $val['pricing_total'] = 0;
            }
			
			//销售总额 - 场次
			$val['price_total'] = Rounding($val['sales_price'] * $val['pricing_num']);
			//扣除成本销售总额 - 场次
			$val['sales_priceTotal'] = Rounding($val['price_total'] - $val['round_priceTotal']);
			//50应发
			$val['Company50_price'] = Rounding($val['pricing_total'] - ($val['pricing_total'] * $CompanyExtract['Company50']/100));
			//55应发
			$val['Company55_price'] = Rounding($val['pricing_total'] - ($val['pricing_total'] * $CompanyExtract['Company55']/100));
			//55应发
			$val['Company60_price'] = Rounding($val['pricing_total'] - ($val['pricing_total'] * $CompanyExtract['Company60']/100));
            $val['should_price'] = $val[$should_price];
			//4000折合
			$val['into_40'] = Rounding(($val['pricing_total'] - $val['should_price'])/$SalesPrice_5);
			//2986折合
			$val['into_29'] = Rounding($val['pricing_total']/$SalesPrice_1);
			//单个信息
			$arr['all'][$val['id']]['round'][] = [
                                        'pricing_type'=>$val['pricing_type'] ?? 0,
										'pricing_price'=>$val['pricing_price'] ?? 0,
                                        'sales_price'=>$val['sales_price'] ?? 0,
                                        'data'=>$val['data'] ?? 0,
										'data_info'=>$val['data_info'] ?? 0,
										'round_priceTotal'=>$val['round_priceTotal'] ?? 0,
                                        'pricing_total'=>$val['pricing_total'] ?? 0,
										'price_total'=>$val['price_total'] ?? 0,
										'sales_priceTotal'=>$val['sales_priceTotal'] ?? 0,
										'pricing_num'=>$val['pricing_num'] ?? 0,
										'round_num'=>$val['round_num'] ?? 0,
										'should_price'=>$val['should_price'] ?? 0,
										'round_price'=>$val['round_price'] ?? 0,
										'desc'=>$val['desc'] ?? '',
										'Company50_price'=>$val['Company50_price'] ?? 0,
										'Company55_price'=>$val['Company55_price'] ?? 0,
										'Company60_price'=>$val['Company60_price'] ?? 0,
										'into_29'=>$val['into_29'] ?? 0,
										'into_40'=>$val['into_40'] ?? 0,
									   ];
			$arr['total']['sales_priceTotal'] += $val['sales_priceTotal']?:0;
            $arr['total']['pricing_total'] += $val['pricing_total']?:0;
			$arr['total']['price_total'] += $val['price_total']?:0;
			$arr['total']['pricing_num'] += $val['pricing_num']?:0;
			$arr['total']['round_num'] += $val['round_num']?:0;
			$arr['total']['round_priceTotal'] += $val['round_priceTotal']?:0;
			$arr['total']['Company50_price'] += $val['Company50_price']?:0;
			$arr['total']['Company55_price'] += $val['Company55_price']?:0;
			$arr['total']['Company60_price'] += $val['Company60_price']?:0;
			$arr['total']['should_price'] += $val['should_price']?:0;
			$arr['total']['into_29'] += $val['into_29']?:0;
			$arr['total']['into_40'] += $val['into_40']?:0;
			unset($val);
		}
		foreach($arr['all'] as $kk=>&$vv){
		
			$vv['lecturer_name'] = TableField('Lecturer','name',$vv['lecturer_id']);
			$vv['subject_name'] = TableField('Subject','name',$vv['subject_id']);
		}
		
		return $arr;
	}
}
if (!function_exists('GetUserRoundExtractAll')) {
	/**
	 * 获取周用户提成 一轮书
	 * @return array
	 * @author gzy
	 * @time 2018年11月9日 15:00:00 
	 */
	function GetUserRoundExtractAll($User = [],$id = NULL,$true = FALSE){
		if(empty($User)||empty($id)) return [];
		$pid = TableField('AuthRule','id','extract/index','name');
		$AuthInfo = TableList('AuthRule',$pid,'pid',[],'weigh','desc');
		$Round_analysis  = GetRoundAnalysisAll('Round_analysis',$id);
		$Analysis  = GetAnalysisAll('Analysis',$id);
		$data = [];
		$Round_analysis['total']['should_price_average'] = $Round_analysis['total']['should_price'] ? Rounding($Round_analysis['total']['should_price']/2):0;
		$data['Round_analysis'] = $Round_analysis;
		$data['Analysis'] = $Analysis;
		//分成方式
		$data['division_method_round'] = TableField('Week','division_method_round',$id,'id');
		$info = [
			'User'=>[],
			'Total'=>[
				'week_total_round' => 0,
				'week_total_round_one' => 0,
                'week_total_round_two' => 0,
                'week_total_integral_otreach' => 0,
				'week_total_integral_books' => 0,
				
			
			],
		];	
		$RoundExtract =	GetBaseInfo('RoundExtract');
		//判断销售过百不过百
		if(($Round_analysis['total']['into_29']+$Analysis['total']['into_cost_29']) >= $RoundExtract['StandardNum']){
			$data['StandardNum'] = $RoundExtract['StandardNum_egt'];
			$data['StandardNum']['type'] = 'egt';
		}else{
			$data['StandardNum'] = $RoundExtract['StandardNum_lt'];
			$data['StandardNum']['type'] = 'lt';
		}
		$extract_num = [
			'manage'=>0,
			'fmanage'=>0,
		];
		//print_r($data);die;
		if($data['division_method_round'] == 1) $extract_num['all'] = 0;
        //本公司外联总积分
        $info['Total']['week_total_integral_otreach'] = array_sum(array_map(function($vss){return $vss['integral_otreach'];}, $User));
        //本公司图书经理总积分
	    $info['Total']['week_total_integral_books'] = array_sum(array_map(function($vss){return $vss['integral_books'];}, $User));
		foreach($User as $key=>&$val){
			$val['week_total_round_one'] = 0;
			$val['count_round'] = 1;
			$val['extract_round'] = [];
			if(!empty($val['position'])){
				$data['position'] = $val['position'];
				$data['userid'] = $val['userid'];
				$data['round_proportion'] = $val['round_proportion'];
                $data['integral_proportion'] = 0;
                $data['books_proportion'] = 0;
                //更改一轮书提成分配方式
                if($info['Total']['week_total_integral_otreach'] > 0 && $val['integral_otreach'] >0){
				    $data['integral_proportion'] = $val['integral_proportion'] =  Rounding($val['integral_otreach']/$info['Total']['week_total_integral_otreach'] * 100);
                }
                if($info['Total']['week_total_integral_books'] > 0  && $val['books_proportion'] > 0 ){
				    $data['books_proportion'] = $val['books_proportion'] =  Rounding($val['integral_books']/$info['Total']['week_total_integral_books'] * 100);
                }

				$extract_round = GetUserExtractOne(3,$id,$data);
				if(!empty($extract_round)){
					$val['extract_round'] = $extract_round['extract_round']??[];
					$val['week_total_round'] = $val['week_total_round_one'] = $extract_round['week_total_round_one'];
					if($data['division_method_round'] == 1){
						$extract_num['all']++;
					}
					if(isset($val['extract_round']['manage'])) $extract_num['manage']++;
					if(isset($val['extract_round']['fmanage'])) $extract_num['fmanage']++;
				}
				unset($extract_round);
				$val['count_round'] = count($val['extract_round']);
				$info['Total']['week_total_round_one'] += $val['week_total_round_one'];
			}
		}

		//判断第二部分分成是人均还是百分比
		if($data['division_method_round'] == 1){
			//print_R($User);die;
			foreach($User as $kk=>&$vv){
				if(!empty($vv['extract_round']) && $extract_num['all']){
					$price_one = 0;
					$price_two = 0;
					//判断总经理和副总的人数并平均
					if(isset($vv['extract_round']['manage'])&& $extract_num['manage']){
						$price_one += $vv['extract_round']['manage']['price'] = Rounding($vv['extract_round']['manage']['price']/$extract_num['manage']);
					}
					if(isset($vv['extract_round']['fmanage'])&& $extract_num['fmanage']){
						$price_one += $vv['extract_round']['fmanage']['price'] = Rounding($vv['extract_round']['fmanage']['price']/$extract_num['fmanage']);
					}
						
					$vv['week_total_round_two'] = $price_two = Rounding($Round_analysis['total']['should_price_average']/$extract_num['all']);
					$vv['week_total_round_one'] += $price_one;
					$vv['week_total_round'] += $price_one;
					$vv['week_total_round'] += $price_two;
					$info['Total']['week_total_round_one'] += $price_one;
					$info['Total']['week_total_round_two'] += $price_two;
					unset($price_one,$price_two);
				}
			}
		}else{
			foreach($User as $kk=>&$vv){
				if(!empty($vv['extract_round'])){
					$price_one = 0;
					$price_two = 0;
					//判断总经理和副总的人数并平均
					if(isset($vv['extract_round']['manage'])&& $extract_num['manage']){
						$price_one += $vv['extract_round']['manage']['price'] = Rounding($vv['extract_round']['manage']['price']/$extract_num['manage']);
					}
					if(isset($vv['extract_round']['fmanage'])&& $extract_num['fmanage']){
						$price_one += $vv['extract_round']['fmanage']['price'] = Rounding($vv['extract_round']['fmanage']['price']/$extract_num['fmanage']);
					}
					//第二部分提成
					$price_two  =  Rounding($Round_analysis['total']['should_price_average'] *$vv['round_proportion']/100);
					//外联80
					if(isset($vv['extract_round']['outreach80'])){
						$price_two = Rounding($price_two*80/100);
					}
					$vv['week_total_round_one'] += $price_one;
					$vv['week_total_round_two'] = $price_two;
					$vv['week_total_round'] +=$price_one;
					$vv['week_total_round'] +=$price_two;
					$info['Total']['week_total_round_one'] += $price_one;
					$info['Total']['week_total_round_two'] += $price_two;
					unset($price_one,$price_two);
				}
			}
		}
		$info['Total']['week_total_round'] = $info['Total']['week_total_round_one']+ $info['Total']['week_total_round_two'];
		//print_r($User);die;
		$info['User'] = $User;
        
		if($true){
			foreach($info['User'] as $k=>$v){
				$extract_round = '';
				if(!empty($v['extract_round']))$extract_round = serialize($v['extract_round']);
				$info['GenerateUser'][$k] = [
					'id'=>$v['id'],
					'week_total_round'=>$v['week_total_round'],
					'week_total_round_one'=>$v['week_total_round_one'],
					'week_total_round_two'=>$v['week_total_round_two'],
					'count_round'=>$v['count_round'], 
                    'extract_round'=>$extract_round,
                    'integral_proportion'=>$v['integral_proportion'],
					'books_proportion'=>$v['books_proportion'],
					];
			
			 }
		}
		return $info;
	
	}
}
if (!function_exists('GetUserExtractOne')) {
	/**
	 * 获取周用户提成 单个
	 * @return type 类型  1 单部门的个人 (提分) 2 单个人 一周数据  3 单部门的个人（一轮书）
	 * @return id   ID  如果类型是1此id为周id 如果是2 此id为用户id 
	 * @return data 数据
	 * @author gzy
	 * @time 2018年9月17日 15:00:00
	 */
	function GetUserExtractOne($type = NUll,$id = NULL,$data = []){
		if(empty($type)||empty($id)) return [];
		if(!isset($data['AuthInfo'])){
			$pid = TableField('AuthRule','id','extract/index','name');
			$data['AuthInfo'] = TableList('AuthRule',$pid,'pid',[],'weigh','desc');
		}
		$info = [];
		switch ($type) {
			 case '1':
				$info['week_total'] = 0;
				$info['into_one_29'] = 0;
				$info['no_ticket_total'] = 0;
				foreach($data['AuthInfo'] as $key=>$val){
					$true = GetCheck($val['name'],$data['position']);
					if($true){
						switch ($val['name']) {
						//总经理提成
						 case 'extract/manage':
							$info['extract']['manage']['price'] = Rounding($data['extract']['manage']['price'] * $data['extract']['manage']['his']/100);
							$info['extract']['manage']['title'] = $val['title'];
							break;
						//副总经理提成
						 case 'extract/fmanage':
						    $info['extract']['fmanage']['price'] = Rounding($data['extract']['manage']['price'] * $data['extract']['manage']['deputyhis']/100);
							$info['extract']['fmanage']['title'] = $val['title'];
							
							break;
						//外联提成
						 case 'extract/outreach':
							$info['extract']['outreach']['price'] = $data['outreach_info'][$data['userid']]??0;
							$info['into_one_29'] += $data['into_one_29'][$data['userid']]??0;
							$info['extract']['outreach']['title'] = $val['title'];
							$info['week_total'] += $info['extract']['outreach']['price'];
							break;
						//外联80提成
						 case 'extract/outreach80':
							$info['extract']['outreach80']['price'] = isset($data['outreach_info'][$data['userid']]) ? Rounding($data['outreach_info'][$data['userid']]*80/100):0;
						    $info['into_one_29'] += $data['into_one_29'][$data['userid']]??0;
							$info['extract']['outreach80']['title'] = $val['title'];
							$info['week_total'] += $info['extract']['outreach80']['price'];
							break;
						//会务提成
						 case 'extract/meeting':
							$info['extract']['meeting']['price'] = $data['extract']['meeting']??0;
							$info['extract']['meeting']['title'] = $val['title'];
							if($data['division_method'] == 2){
								$info['extract']['meeting']['price'] = Rounding($info['extract']['meeting']['price']*$data['proportion']/100);
								$info['week_total'] += $info['extract']['meeting']['price'];
							}
							break;
						//客服提成
						 case 'extract/service':
							$info['extract']['service']['price'] = $data['extract']['service']??0;
							$info['extract']['service']['title'] = $val['title'];
							if($data['division_method'] == 2){
								$info['extract']['service']['price'] = Rounding($info['extract']['service']['price']*$data['proportion']/100);
								$info['week_total'] += $info['extract']['service']['price'];
								//$info['no_ticket_total'] += isset($data['no_ticket']) ? Rounding($data['no_ticket']*$data['NoTicketRate']['Service']/100*$data['proportion']/100):0;
							}
							break;
						//财务提成
						 case 'extract/finance':
							$info['extract']['finance']['price'] = $data['extract']['finance']??0;
							$info['extract']['finance']['title'] = $val['title'];
							if($data['division_method'] == 2){
								$info['extract']['finance']['price'] = Rounding($info['extract']['finance']['price']*$data['proportion']/100);
								$info['week_total'] += $info['extract']['finance']['price'];
							}
							break;
						}
					}
					
				}
				break;
			 case '2':
				 //此价钱没有加上大区、营销中心总经理提成，放在另外的地方计算
				 $info['week_total'] = 0;
				foreach($data['AuthInfo'] as $key=>$val){
					$true = GetCheck($val['name'],$data['position']);
					if($true){
						switch ($val['name']) {
						//股份提成
						 case 'extract/shares':
							$shares_num = 0;
							if(GetCheck('extract/point_shares',$data['position'])){
								//加上提分
								$shares_num += $data['into_36'];
							}
							if(GetCheck('extract/books_shares',$data['position'])){
								//加上一轮书
								$shares_num += $data['into_40_round'];
							}
							if(GetCheck('extract/one_shares',$data['position'])){
								$info['extract']['shares']['price'] = Rounding($shares_num * $data['shares_price']);
								$info['extract']['shares']['title'] = '单价提成';
							}else{
								$shares_price = Rounding($shares_num * $data['shares_price']);
								$info['extract']['shares']['price'] = Rounding($shares_price * $data['shares_proportion']/100);
								$info['extract']['shares']['title'] = $val['title'];
							}
							$info['week_total'] += $info['extract']['shares']['price'];
							break;
						//大区经理提成
						 case 'extract/area_manage':
								$area_num = ['num'=>0,'into_29'=>0,'into_36'=>0,'price'=>0,'total_price'=>0];
							 	$top = ValueExists(GetBaseInfo('Dept'),$data['department']);
								$Standard = GetBaseInfo('AreaExtract')['Standard'];
								$Standard_lt = GetBaseInfo('AreaExtract')['Standard_lt'];
								$Standard_egt = GetBaseInfo('AreaExtract')['Standard_egt'];
								$Standard150 = GetBaseInfo('AreaExtract')['Standard150'];
								$Standard150_lt = GetBaseInfo('AreaExtract')['Standard150_lt'];
								$Standard150_egt = GetBaseInfo('AreaExtract')['Standard150_egt'];
								if(!empty($top)){
						
									$topArr = implode(',',$top);
									$where = "w.start_time = '".$data['time']['start_time']."' and w.end_time = '".$data['time']['end_time']."' and dept.parentid in(".$topArr.")";
									$area_manage = TableListSqlQuery('DeptWeek',$where);
									if(!empty($area_manage)){
										foreach($area_manage as $kk=>&$vv){
											//单部门提成
											switch (true) {
											 case $vv['into_29'] >= $Standard:
												$vv['price'] = $vv['into_36'] * $Standard_egt;
												break;
											 case $vv['into_29'] < $Standard && $vv['into_29'] > 0:
												$vv['price'] = $vv['into_36'] * $Standard_lt;
												break;
											 default:
												$vv['price'] = 0;
												break;
											}
											$area_num['into_29'] += $vv['into_29'];
											$area_num['into_36'] += $vv['into_36'];
											$area_num['num'] += 1;
											$area_num['total_price'] +=$vv['price'];
										}
										if($area_num['num']){
											$area_num['into_29'] = Rounding($area_num['into_29']/$area_num['num']);
											//总提成
											switch (true) {
											 case $area_num['into_29'] >= $Standard150:
												$area_num['price'] = $area_num['into_36'] * $Standard150_egt;
												break;
											 case $area_num['into_29'] < $Standard150 && $area_num['into_29'] > 0:
												$area_num['price'] = $area_num['into_36'] * $Standard150_lt;
												break;
											 default:
												$area_num['price'] = 0;
												break;
											}
										}
									}

									unset($where);
									$info['extract']['area_manage']['area_num'] = $area_num;
									$info['extract']['area_manage']['area'] = $area_manage;
								}
							break;
						//营销中心总经理提成
						 case 'extract/core_manage':
							$info['extract']['core_manage']['price'] = $data['into_36'] * GetBaseInfo('AreaExtract')['CoreManage'];
							$info['extract']['core_manage']['title'] = $val['title'];
							break;
						//签约提成
						 case 'extract/contract':
							$contract_num = 0;
							if($data['contract_price']){
							    //签约金额对应套数
								$set_num = Rounding($data['contract_price']/10*0.3);
								//36折合+一轮书
								$contract_num = $data['into_36'] + $data['into_40_round'];
								$info['extract']['contract']['price'] = Rounding($set_num * $contract_num);
								$info['extract']['contract']['title'] = $val['title'];
								$info['week_total'] += $info['extract']['contract']['price'];
								unset($set_num);
							}
							break;
						//管理提成
						 case 'extract/admin':
							$admin_num = 0;
							if(GetCheck('extract/point_admin',$data['position']) && GetCheck('extract/books_admin',$data['position'])){
								//加上提分 
								$admin_num += $data['into_36'];
								$info['extract']['admin']['contract'] = 1;
							}elseif(GetCheck('extract/books_admin',$data['position'])){
								//加上一轮书
								$admin_num += $data['into_40_round'];
								$info['extract']['admin']['contract'] = 0;
							}
							$info['extract']['admin']['price'] = Rounding($admin_num * $data['unit_price']);
							$info['extract']['admin']['title'] = $val['title'];
							$info['week_total'] += $info['extract']['admin']['price'];	
							break;
						}
					}
					
				}
				break;
			 case '3':
				$info['week_total_round_one'] = 0;
				$info['week_total_round_two'] = 0;
					$should_price_average = $data['Round_analysis']['total']['should_price_average'];
					$StandardNum = $data['StandardNum'];
					foreach($data['AuthInfo'] as $key=>$val){
						$true = GetCheck($val['name'],$data['position']);
						if($true){
							switch ($val['name']) {
							//总经理提成
							 case 'extract/manage':
								$info['extract_round']['manage']['price'] = Rounding($should_price_average * $StandardNum['ExtractHis']/100);
								$info['extract_round']['manage']['title'] = $val['title'];
								break;
							//副总经理提成
							 case 'extract/fmanage':
								$info['extract_round']['fmanage']['price'] = Rounding($should_price_average * $StandardNum['ExtractDeputyHis']/100);
								$info['extract_round']['fmanage']['title'] = $val['title'];
							
								break;
							//外联提成
							 case 'extract/outreach':
								$info['extract_round']['outreach']['price'] = Rounding(($should_price_average * $StandardNum['ExtractOutreachHis']/100)*$data['integral_proportion']/100);
								$info['extract_round']['outreach']['title'] = $val['title'];
								$info['week_total_round_one'] += $info['extract_round']['outreach']['price'];
							
								break;
							//外联80提成
							 case 'extract/outreach80':
								$info['extract_round']['outreach80']['price'] = Rounding((($should_price_average * $StandardNum['ExtractOutreachHis']/100)*$data['integral_proportion']/100)*80/100);
								$info['extract_round']['outreach80']['title'] = $val['title'];
								$info['week_total_round_one'] += $info['extract_round']['outreach80']['price'];
								break;
							//会务提成
							 case 'extract/meeting':
								$info['extract_round']['meeting']['title'] = $val['title'];
								break;
							//客服提成
							 case 'extract/service':
								$info['extract_round']['service']['title'] = $val['title'];
								
								break;
							//财务提成
							 case 'extract/finance':
								$info['extract_round']['finance']['title'] = $val['title'];
								
								break;
							//图书经理提成
							 case 'extract/books':
								$info['extract_round']['books']['price'] = Rounding(($should_price_average * $StandardNum['ExtractBooksHis']/100)*$data['books_proportion']/100);
								$info['extract_round']['books']['title'] = $val['title'];
								$info['week_total_round_one'] += $info['extract_round']['books']['price'];
								break;
							}
							
						}
					}
				
				break;
			 default:
				$info = [];
				break;
		}
		return $info;
	}
}
if (!function_exists('GenerateWeekAll')) {
	/**
	 * 生成周数据 多个
	 * @return type 类型  1 单周  2 单个人 一周数据  
	 * @return id   ID  如果类型是1此id为周id 如果是2 此id为用户id 
	 * @return data 数据
	 * @author gzy
	 * @time 2018年9月17日 15:00:00
	 */
	function GenerateWeekAll($date = []){
		if(empty($date)) return false;
		$info = [];
		$i = 0;
		$arr = [];
		$GenerateUser = [];
        $GenerateUserRound = [];
		$SeasonInfo = [];
	
		foreach($date as $key=>$val){
			$arr[$key] = ['into_36'=>0,'into_29'=>0,'into_cost_29'=>0,'into_40_round'=>0,'into_29_round'=>0];
			$data = [];
			if(!empty($val)){
				$time = explode(',',$val);
				$where = "`delete_status` = 1 and `start_time` = '".$time[0]."' and `end_time` = '".$time[1]."'";
				$data = array_column(TableListSqlQuery('Field',$where,'id,name,integral,grade','hdyj_finance_extract_week','order by integral Desc'),null,'id');
              
				if(!empty($data)){
					foreach($data as $k=>$v){
						$User = [];
                        $info[$i] = [
                            'id'=>$k,
                            'userextract'=>[
                                'GenerateUser'=>[]
                            ],  
                            'userextract_round'=>[
                                'GenerateUser'=>[]
                            ],
                            'integral'=>0,
                        ];
						$info[$i]['id'] = $k;

						//提分信息
						$info[$i]['analysis'] = GetAnalysisAll('Analysis',$k);
                        //场次新增生成字段  外联提成标准
                        //$season_info[$i] =  array_values(array_map(function($vss){return ['id'=>$vss['id'],'outreach_extract'=>$vss['OutreachExtract']];}, $info[$i]['analysis']['all']));
                        $season_info[$i] =  array_map(function($vss){return ['id'=>$vss['id'],'outreach_extract'=>$vss['OutreachExtract']];}, $info[$i]['analysis']['all']);
                        $SeasonInfo = array_merge($SeasonInfo,$season_info[$i]);
                        //print_r($season_info);die;
						$info[$i]['total_text'] = serialize($info[$i]['analysis']['total']);
						$info[$i]['into_36'] = $info[$i]['analysis']['total']['into_36'];
						$info[$i]['into_29'] = $info[$i]['analysis']['total']['into_29'];
						$info[$i]['into_cost_29'] = $info[$i]['analysis']['total']['into_cost_29'];
						//一周所有36和29折合
						$arr[$key]['into_36'] += $info[$i]['analysis']['total']['into_36'];
						$arr[$key]['into_29'] += $info[$i]['analysis']['total']['into_29'];
						$arr[$key]['into_cost_29'] += $info[$i]['analysis']['total']['into_cost_29'];
						$info[$i]['books'] = GetAnalysisBooks('Analysis',$k,true);
                        //公司积分+外联积分
                        $info[$i]['integral'] = IntegralPlus($k);
						//排序修改
						$User = TableListSqlQuery('UserExtract',"u.extract_week = '".$k."'");
						//$User = TableList('User',$k,'extract_week');
						if(!empty($User)) $info[$i]['userextract'] = GetUserExtractAll($User,$k,true);
						$GenerateUser = array_merge($GenerateUser,$info[$i]['userextract']['GenerateUser']);
						unset($info[$i]['userextract']['GenerateUser']);
						$info[$i]['analysis'] = serialize($info[$i]['analysis']);
						$info[$i]['userextract'] = serialize($info[$i]['userextract']);
                        
						//一轮书信息
						$info[$i]['analysis_round'] = GetRoundAnalysisAll('Round_analysis',$k);
						$info[$i]['total_text_round'] = serialize($info[$i]['analysis_round']['total']);
						$info[$i]['into_40_round'] = $info[$i]['analysis_round']['total']['into_40'];
						$info[$i]['into_29_round'] = $info[$i]['analysis_round']['total']['into_29'];
						//一周所有40和29折合
						$arr[$key]['into_40_round'] += $info[$i]['analysis_round']['total']['into_40'];
						$arr[$key]['into_29_round'] += $info[$i]['analysis_round']['total']['into_29'];
						if(!empty($User)) $info[$i]['userextract_round'] = GetUserRoundExtractAll($User,$k,true);
						$GenerateUserRound = array_merge($GenerateUserRound,$info[$i]['userextract_round']['GenerateUser']);
						unset($info[$i]['userextract_round']['GenerateUser']);
						$info[$i]['analysis_round'] = serialize($info[$i]['analysis_round']);
                        $info[$i]['userextract_round'] = serialize($info[$i]['userextract_round']);

                        // $info[$i]['integral'] = $v['integral'];
						$i++;
					}
				}
				unset($time,$where,$data,$User,$key,$val);
			}
		}  
       
    
		//生成周成员 做完生成所有用户 去掉注释
		if(!empty($GenerateUser)) model(GetTableModel('User'))->saveAll($GenerateUser);
		//生成周成员 做完生成所有用户 一轮书
        if(!empty($GenerateUserRound)) model(GetTableModel('User'))->saveAll($GenerateUserRound);
        //生成场次新字段 
		if(!empty($SeasonInfo)) model(GetTableModel('Season'))->saveAll($SeasonInfo);

		//生成周数据 
		if(!empty($info)){ 
            $info = GenerateWeekRanking($info);
            $saveweek = model(GetTableModel('Week'))->saveAll($info);
        }
		//$saveweek = 1;
		//print_R($saveweek);die;
		if(isset($saveweek)){
			$result = GenerateWeekAllUser($date,$arr);
		}
			
		return true;
	}
}
if (!function_exists('GenerateWeekRanking')) {
     /**
     * 生成本周公司排名 挡位 
     * @return array
     * @author gzy
     * @time 2018年12月26日 16:00:31
     */
    function  GenerateWeekRanking($data=[]){
            if(empty($data)) return [];
            array_multisort(array_column($data, 'integral'), SORT_DESC, $data);
            $count = count($data);
            $divisor = substr(sprintf("%.2f",$count/3),0,-1);
            $divisor_arr = explode(".",$divisor);
            if($count % 3 != 0){
                $divisible = $divisor_arr[1]/3;
            }else{
                $divisible = 0;
            }
            //0 1 2 
            for($i=0; $i<3; $i++){
                
                if((($divisible * $i)%2 == 0)&& $i!=0 && $divisible!=0){
                    if($i == 1){
                        $arr[] = array_slice($data,$i*$divisor_arr[0],$divisor_arr[0]+$i);

                    }else{
                        $arr[] = array_slice($data,$i*$divisor_arr[0]+$divisible-1,$divisor_arr[0]+$i);

                    }
                }else{
                    $arr[] = array_slice($data,$i*$divisor_arr[0],$divisor_arr[0]);
                }
            }
            
             $asrr = GenerateWeekRankingTest(0,$arr,$count);
              
             $Grade = [
                        ['grade'=>1],
                        ['grade'=>2],
                        ['grade'=>3]
                    ];
           
            for($i=0; $i<3; $i++){
                array_walk($asrr[$i],function (&$value,$key,$Grade) {$value = array_merge($value, $Grade);}, $Grade[$i]);
                //$asrr[$i] = array_column($asrr[$i],null,'id');
            }
            return array_column(array_merge($asrr[0],$asrr[1],$asrr[2]),null,'id');        
           
    }
}
if (!function_exists('GenerateWeekRankingTest')) {
       function GenerateWeekRankingTest($a =0,$arr=[],$count){
            $a++;
            if ($a<=$count) {
                if(!empty($arr[1])){
                    if(isset($arr[1][0]['integral']) && isset($arr[0][count($arr[0])-1]['integral'])){
                        if($arr[1][0]['integral'] == $arr[0][count($arr[0])-1]['integral']){
                            array_unshift($arr[1],$arr[0][count($arr[0])-1]);
                            unset($arr[0][count($arr[0])-1]);
                        }
                    }
                }
                if(!empty($arr[2])){
                    if(isset($arr[2][0]['integral']) && isset($arr[1][count($arr[0])-1]['integral'])){
                        if($arr[2][0]['integral'] == $arr[1][count($arr[1])-1]['integral']){
                            array_unshift($arr[2],$arr[1][count($arr[1])-1]);
                            unset($arr[1][count($arr[1])-1]);
                        }
                    }
                }
                $arr = GenerateWeekRankingTest($a,$arr,$count);
              }
             return $arr;   
       }
                
}
if (!function_exists('GenerateWeekAllUser')) {
	/**
	 * 生成所有用户周提成 
	 * @return array
	 * @author gzy
	 * @time 2018年9月27日 10:00:21
	 */
	function GenerateWeekAllUser($date = [],$arr = []){
			if(empty($arr) || empty($date)) return [];
			$userinfo = TableListSqlQuery('UserInfo',"info.`status` = 2");
			$pid = TableField('AuthRule','id','extract/index','name');
			$data = [];
			$data['AuthInfo'] = TableList('AuthRule',$pid,'pid',[],'weigh','desc');
			$isset = [];
			$public = [];
			foreach($date as $key=>$val){
				$data['into_36'] = $arr[$key]['into_36'];
				$data['into_29'] = $arr[$key]['into_29'];
				$data['into_cost_29'] = $arr[$key]['into_cost_29'];
				$data['into_40_round'] = $arr[$key]['into_40_round'];
				$data['into_29_round'] = $arr[$key]['into_29_round'];
				$isset[$key]['userinfo'] = $userinfo;
				//管理提成相关数据
				$public[$key]['total'] = ['contract_total'=>0,'admin_num'=>0];
				if(!empty($val)){
					$time = explode(',',$val);
					$where = "w.`start_time` = '".$time[0]."' and w.`end_time` = '".$time[1]."'";
								
					$data['time'] = ['start_time'=>$time[0],'end_time' => $time[1]];
					if(!empty($isset[$key]['userinfo'])){
						foreach($isset[$key]['userinfo'] as $kk=>&$vv){
							$vv['extract'] = [];
							$vv['week_total'] = 0;
							if(!empty($vv['position'])){
								$data['contract_price'] = $vv['contract_price'] ?? 0;
								$data['unit_price'] = $vv['unit_price'] ?? 0;
								$data['shares_price'] = $vv['shares_price'] ?? 0;
								$data['shares_proportion'] = $vv['shares_proportion'] ?? 0;
								$data['position'] = $vv['position'] ?? '';
								$data['department'] = $vv['department'] ?? '';
								//print_R($data);die;
								$extract = GetUserExtractOne(2,$vv['userid'],$data);
								if(!empty($extract)){
									$vv['extract'] = $extract['extract'] ?? [];
									$vv['week_total'] = $extract['week_total'] ?? 0;
								}
							}
							$vv['total'] =[
									//提分版税	
									'point_total'=>0,
									//图书版税
									'books_total'=>0,
									//应发版税
									'answer_total'=>0,
									//签约版税
									'contract_total'=>0,
									//股份版税
									'shares_total'=>0,
									//版税合计
									'week_total'=>0,
									//无票合计
									'no_ticket_total'=>0,
									//参会版税
									'admission_fee'=>0,
									//本周扣税
									'tax_total'=>0,
									//欠缴税金
									'tax_owe'=>0,
									//已缴无票
									'no_ticket_noowe'=>0,
									//欠扣无票
									'no_ticket_owe'=>0,
									//实发版税
									'real_hair'=>0
								];
							if($vv['status_week'] == 2){
								//如果有周提成则去查询此周有没有他的提成
								$total = TableListSqlQuery('UserWeek',$where." and u.userid ='".$vv['userid']."'");
								$vv['total'] = array_merge($vv['total'],$total[0]);
								$vv['total']['point_total'] = $vv['total']['week_total'] - $vv['total']['admission_fee'];
								$vv['total']['books_total'] = $vv['total']['books_total'];
							}
							$total = 0;
							//大区经理提成判断
							if(isset($vv['extract']['area_manage'])){
								//判断是否有营销总经理提成
								if(isset($vv['extract']['core_manage'])){
									$total += $vv['extract']['core_manage']['price'] + $vv['extract']['area_manage']['area_num']['total_price'];
								}else{
									$total += $vv['extract']['area_manage']['area_num']['price']?:$vv['extract']['area_manage']['area_num']['total_price'];
								}
							}
							//判断签约提成总价 用于计算管理提成
							if(isset($vv['extract']['contract']['price'])){
								$public[$key]['total']['contract_total'] += $vv['extract']['contract']['price'];
								$vv['total']['contract_total'] = $vv['extract']['contract']['price'];
							}
							//判断股份提成
							if(isset($vv['extract']['shares']['price'])) 
							$vv['total']['shares_total'] += $vv['extract']['shares']['price'];
							//获取管理提成总人数
							if(isset($vv['extract']['admin'])){
								if($vv['extract']['admin']['contract']){
									$public[$key]['total']['admin_num'] += 1;
								}
							}else{
								//算其他提成
								$vv['total']['point_total'] += $total;
								$vv['total']['answer_total'] = $vv['total']['point_total'] + $vv['total']['books_total'];
								$vv['total']['week_total'] +=  $total + $vv['week_total'];
								$vv['total']['tax_total'] = $vv['total']['week_total']?Rounding($vv['total']['week_total']*GetBaseInfo('Public')['TaxSet']/100):0;
								$tax_owe = $vv['total']['week_total'] - $vv['total']['admission_fee'] - $vv['total']['tax_total'];
								if($tax_owe < 0){
									$vv['total']['tax_owe'] = abs($tax_owe);
									$vv['total']['no_ticket_owe'] = $vv['total']['no_ticket_total'];
								}else{
									$no_ticket_noowe = $tax_owe - $vv['total']['no_ticket_total'];
									if($no_ticket_noowe < 0){
										$vv['total']['no_ticket_owe'] = abs($no_ticket_noowe);
									}else{
										$vv['total']['no_ticket_noowe'] = $vv['total']['no_ticket_total'];
										$vv['total']['real_hair'] = $no_ticket_noowe;
									}
								}
							}
							unset($no_ticket_noowe,$total,$data['contract_price'],$data['unit_price'],$data['shares_price'],$data['shares_proportion'],$data['position'],$data['department']);

						}
					}
				}
				unset($key,$val,$data['into_36'],$data['into_29'],$data['time'],$where,$time);
			}
			//print_R($public);die;

			$saveAll = [];
			$i = 0;
			foreach($date as $key=>$val){
				$data['into_36'] = $arr[$key]['into_36'];
				$data['into_29'] = $arr[$key]['into_29'];
				if(!empty($val)){
					$time = explode(',',$val);
					$where = "`start_time` = '".$time[0]."' and `end_time` = '".$time[1]."'";
					$data['time'] = ['start_time'=>$time[0],'end_time' => $time[1]];
					//删除之前的
					model(GetTableModel('Info'))->where($where)->delete();
					if(!empty($isset[$key]['userinfo'])){
						foreach($isset[$key]['userinfo'] as $k=>&$v){
							
							//算管理提成
							if(isset($v['extract']['admin'])){
								if($v['extract']['admin']['contract']){
									$cotract_price = Rounding($public[$key]['total']['contract_total']/$public[$key]['total']['admin_num']);
									$v['extract']['admin']['price'] = $v['extract']['admin']['price'] - $cotract_price;
									$v['week_total'] = $v['week_total'] - $cotract_price;
								
								}
								$v['total']['shares_total'] += $v['extract']['admin']['price'];
								$v['total']['week_total'] =  $v['week_total'];
								$v['total']['tax_total'] = $v['total']['week_total']?Rounding($v['total']['week_total']*GetBaseInfo('Public')['TaxSet']/100):0;
								$tax_owe = $v['total']['week_total'] - $v['total']['admission_fee'] - $v['total']['tax_total'];
								if($tax_owe < 0){
									$v['total']['tax_owe'] = abs($tax_owe);
									$v['total']['no_ticket_owe'] = $v['total']['no_ticket_total'];
								}else{
									$no_ticket_noowe = $tax_owe - $v['total']['no_ticket_total'];
									if($no_ticket_noowe < 0){
										$v['total']['no_ticket_owe'] = abs($no_ticket_noowe);
									}else{
										$v['total']['no_ticket_noowe'] = $v['total']['no_ticket_total'];
										$v['total']['real_hair'] = $no_ticket_noowe;
									}
								}
							
							}
							$saveAll[$i] = [
								'userid'=>$v['userid'],
								'weigh'=>$v['weigh'],
								'start_time'=>$time[0],
								'end_time'=>$time[1],
								'publish'=>\think\Session::get('admin')['userid'],
								'z_publish'=>\think\Session::get('admin')['userid'],
								
							];
							$saveAll[$i] = array_merge($saveAll[$i],$v['total']);
							unset($cotract_price);
							$i++;
						}
					}
				}
				unset($where,$time);
			}
			$result = model(GetTableModel('Info'))->saveAll($saveAll);
			return true;
	}
}
if (!function_exists('ExcelWeekAll')) {
	/**
	 * 导出数据 
	 * @return array
	 * @author gzy
	 * @time 2018年9月28日 17:35:21
	 */
	function ExcelWeekAll($date = []){
		if(empty($date)) return [];
		set_time_limit(0);
		$excel = new PHPExcel();
		//判断属否存在数据
		$i = 0;
		$total = [];
		$a = 0;
		foreach($date as $key=>$val){
			if(!empty($val)){
				$time = explode(',',$val);
				$where = "`start_time` = '".$time[0]."' and `end_time` = '".$time[1]."'";
				$list = model(GetTableModel('Info'))->where($where)->select();
				foreach ($list as $row) {
					$row->visible(['username_text','cardnumber_text','idnumber_text','point_total','books_total','withhold','answer_total','contract_total','shares_total','admission_fee','week_total','tax_total','tax_total','tax_owe','no_ticket_total','no_ticket_noowe','no_ticket_owe','no_ticket_owe','real_hair','mobile_text']);
				}
				$list = collection($list)->toArray();
				if(empty($list)) continue;
				
				$i++;
				$excel->getProperties()
					->setCreator("gzy")
					->setLastModifiedBy("gzy")
					->setTitle($val)
					->setSubject("周提成表");
			   //从第几行开始
			   $line = 2;
			   $styleArray = array(
                     'font' => array(
                            'size'  => 10,
                            'name'  => 'Verdana'
					 ),
					  'borders' => array(
							'allborders' => array( //设置全部边框
								'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
							),

						),
			   );
				$worksheet = $excel->setActiveSheetIndex($a);
							
				$excel->getActiveSheet()->mergeCells('A1:T1');//合并第一行的单元格
				$excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
				$excel->setActiveSheetIndex($a)->setCellValue('A1', $val.'个人版税明细');//标题
				$excel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);  
				$sss = 0;
				foreach(ExcelWeekField() as $kk=>$vv){
					if($vv['display'] == 3) continue;
					$worksheet->setCellValueByColumnAndRow($sss, $line, __($vv['key']));
					$excel->getActiveSheet()-> getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($sss))->setWidth($vv['width']);
					$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
					$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
					$sss++;
				}
				
				$worksheet->setTitle($val);
				$mynum = 1;//序号
				foreach ($list as $index => $item) {
							$line++;
							$sss = 0;
							foreach(ExcelWeekField() as $kk=>$vv){
								if($vv['display'] == 3) continue;
								if($vv['key'] == 'mynum'){
									$worksheet->setCellValueByColumnAndRow($sss, $line, $mynum);
								}elseif($vv['key'] == 'point_books'){
									$worksheet->setCellValueByColumnAndRow($sss, $line, $item['point_total']+$item['books_total']);
								}elseif($vv['key'] == 'reward'){
									$worksheet->setCellValueByColumnAndRow($sss, $line, 0);
								}else{
									$worksheet->setCellValueByColumnAndRow($sss, $line, $item[$vv['key']]);
								}
								$worksheet->getStyleByColumnAndRow($sss,$line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
								$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
								$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
								//$worksheet->getColumnDimension($sss)->setWidth(50);;
								$sss++;
							}
						$mynum++;
					}
				$line = $line+1;
				//$point_total = array_sum(array_map(function($val){return $val['point_total'];}, $list));
				//$point_total = array_sum(array_map(function($val){return $val['point_total'];}, $list));
				//合计
				$sss = 0;
				foreach(ExcelWeekField() as $kk=>$vv){
					if($vv['display'] == 3) continue;
					if($vv['type'] == 2){
						$vss = [];
						if($vv['key'] == 'point_books'){
							$total[$vv['key']] = $total['point_total'] + $total['books_total'];
						}elseif($vv['key'] == 'reward'){
							$total[$vv['key']] = 0;
						}else{
							$vss[] = $vv['key'];
							for($aa = 0;$aa<count($list);$aa++){
								$vss[$aa] = $vv['key'];
							}
							$total[$vv['key']] = array_sum(array_map(create_function('$val,$vv', 'return $val[$vv];'), $list,$vss));
						}
					}
					$worksheet->setCellValueByColumnAndRow($sss, $line, $total[$vv['key']]??'');
					$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
					$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
					$sss++;
				}
				$excel->getActiveSheet()->mergeCells('A'.$line.':C'.$line.'');//合并第一行的单元格
				$excel->getActiveSheet()->getStyle('A'.$line.'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
				$excel->setActiveSheetIndex($a)->setCellValue('A'.$line.'', '合计');//标题
				//print_R($total);die;
				
				$excel->createSheet();
				unset($worksheet);
				$a++;
			}
		}
	
		if($i>0){
			//删除空的sheet
			$sheetIndex = $excel->getIndex($excel->getSheetByName('Worksheet')); 
			$excel->removeSheetByIndex($sheetIndex);
			return $excel;
		}else{
			return [];
		}
	}
}

if (!function_exists('ExcelWeektaxAll')) {
	/**
	 * 生成并导出数据 月数据 
	 * @return array
	 * @author gzy
	 * @time 2018年9月28日 17:35:21
	 */
	function ExcelWeektaxAll($type,$date = [],$time = NULL){
		if((empty($date) && $type == 1) || empty($type)|| empty($time)) return [];
		$where = "`datemonth` = '".$time."'";
		switch ($type) {
		 case 1:
			$where_ee = '';
			foreach($date as $key=>$val){
				$or = ' or ';
				if($key == 0) $or = '';
				$ti = explode(',',$val);
			    $where_ee .= $or."(`start_time` = '".$ti[0]."' and `end_time` = '".$ti[1]."')";
			 }
			 //获取选择的时间段的合计
			$info = TableListSqlQuery('WeekTaxTotal',$where_ee,' weigh');
			
			$Baseinfo = GetBaseInfo('Tax');
			foreach($info as $kk=>&$vv){
					$tax = 0;	
					//应扣版税
					$vv['answer_tax'] = 0;
					//欠缴税金
					$vv['owe_tax'] = 0;
					//多扣税金
					$vv['repair_tax'] = 0;
					//应发版税
					$vv['answer_hair'] = 0;
					switch (true) {
					 case $vv['week_total'] <= $Baseinfo['Price'] && $vv['week_total'] > 0 && $vv['week_total'] > $Baseinfo['Price_lt']['Price']:
						$vv['answer_tax'] = Rounding(($vv['week_total'] - $Baseinfo['Price_lt']['Price']) * $Baseinfo['Rate']/100);
						break;
					 case $vv['week_total'] > $Baseinfo['Price'] && $vv['week_total'] > 0 :
						$vv['answer_tax'] = Rounding(($vv['week_total'] - ($vv['week_total'] * $Baseinfo['Price_egt']['His']/100)) * $Baseinfo['Rate']/100);
						break;
					default:
						$vv['answer_tax'] = 0;
						break;
					}
					if($vv['tax_owe']) $vv['tax_total'] = $vv['tax_total'] - $vv['tax_owe'];
					$tax = Rounding($vv['answer_tax'] - $vv['tax_total'] );
					if($tax > 0){
						$vv['owe_tax'] = $tax;
						$vv['answer_hair'] = Rounding($vv['real_hair'] - $vv['owe_tax']);
					}elseif($tax < 0){
						$vv['repair_tax'] = abs($tax);
						$vv['answer_hair'] = Rounding($vv['real_hair'] + $vv['repair_tax']);
					}else{
						$vv['answer_hair'] = $vv['real_hair'];
					}
					$vv['answer_hair'] = Rounding($vv['answer_hair'] - $vv['no_ticket_owe']);
					$vv['datemonth'] = $time;
					$vv['publish'] = \think\Session::get('admin')['userid'];
					$vv['z_publish'] = \think\Session::get('admin')['userid'];
					unset($vv['tax_owe']);
			}
			//print_r($info);die;
			//删除之前的
			model(GetTableModel('Month'))->where($where)->delete();
			$result = model(GetTableModel('Month'))->saveAll($info);
			break;
		 case 2:
			break;
		 default:
			return [];
			break;
		}
		
		set_time_limit(0);
		$excel = new PHPExcel();
		//判断属否存在数据
		$i = 1;
		$total = [];
		
		$list = model(GetTableModel('Month'))->where($where)->select();
		$list = collection($list)->toArray();
		if(empty($list)) return [];
		$excel->getProperties()
			->setCreator("gzy")
			->setLastModifiedBy("gzy")
			->setTitle($time)
			->setSubject("月提成表");
	   //从第几行开始
	   $styleArray = array(
			 'font' => array(
					'size'  => 10,
					'name'  => 'Verdana'
			 ),
			  'borders' => array(
					'allborders' => array( //设置全部边框
						'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
					),

				),
	   );
		$key = 0;
		//从第几行开始
		$line = 2;
		$worksheet = $excel->setActiveSheetIndex($key);
		$excel->getActiveSheet()->mergeCells('A1:V1');//合并第一行的单元格
		$excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$excel->setActiveSheetIndex($key)->setCellValue('A1', $time.'个人版税明细');//标题
		$excel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);
		$sss = 0;
		foreach(ExcelWeekField() as $kk=>$vv){
			if($vv['display'] == 2) continue;
			$worksheet->setCellValueByColumnAndRow($sss, $line, $vv['name']);
			$excel->getActiveSheet()-> getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($sss))->setWidth($vv['width']);
			$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
			$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sss++;
		}
		$worksheet->setTitle($time);
		$mynum = 1;//序号
		
		foreach ($list as $index => $item) {
					$line++;
					$sss = 0;
					foreach(ExcelWeekField() as $kk=>$vv){
						if($vv['display'] == 2) continue;
						if($vv['key'] == 'mynum'){
							$worksheet->setCellValueByColumnAndRow($sss, $line, $mynum);
						}else{
							$worksheet->setCellValueByColumnAndRow($sss, $line, $item[$vv['key']]);
						}
						$worksheet->getStyleByColumnAndRow($sss,$line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
						$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
						$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
						//$worksheet->getColumnDimension($sss)->setWidth(50);;
						$sss++;
					}
				$mynum++;
			}
		$line = $line+1;
		//$point_total = array_sum(array_map(function($val){return $val['point_total'];}, $list));
		//$point_total = array_sum(array_map(function($val){return $val['point_total'];}, $list));
		//合计
		$sss = 0;
		foreach(ExcelWeekField() as $kk=>$vv){
			if($vv['display'] == 2) continue;
			if($vv['type'] == 2){
				$vss = [];
				$vss[] = $vv['key'];
				for($aa = 0;$aa<count($list);$aa++){
					$vss[$aa] = $vv['key'];
				}
				$total[$vv['key']] = array_sum(array_map(create_function('$val,$vv', 'return $val[$vv];'), $list,$vss));
				
			}
			$worksheet->setCellValueByColumnAndRow($sss, $line, $total[$vv['key']]??'');
			$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
			$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sss++;
		}
		$excel->getActiveSheet()->mergeCells('A'.$line.':C'.$line.'');//合并第一行的单元格
		$excel->getActiveSheet()->getStyle('A'.$line.'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$excel->setActiveSheetIndex($key)->setCellValue('A'.$line.'', '合计');//标题
		
		$excel->createSheet();
		unset($worksheet);
		if($i>0){
			//删除空的sheet
			$sheetIndex = $excel->getIndex($excel->getSheetByName('Worksheet')); 
			$excel->removeSheetByIndex($sheetIndex);
			return $excel;
		}else{
			return [];
		}
	}
}
if (!function_exists('ExcelBooksWeekAll')) {
	/**
	 * 导出数据 日记账
	 * @return array
	 * @author gzy
	 * @time 2018年9月28日 17:35:21
	 $WeekInfo[$key] = TableListSqlQuery($key,'`extract_week` = '.$id.'');
					foreach($WeekInfo[$key] as $k=>&$v){
						$v['Books_view'] = TableListSqlQuery($key.'_view','`extract_week` = '.$id.' and `day` = '.$v['day'].'');
					}
	 */
	function ExcelBooksWeekAll($date = []){
	
		if(empty($date)) return [];
		set_time_limit(0);
		$url = [];
		$ssss = 0;
		foreach($date as $key=>$val){
			if(!empty($val)){
				$books_arr = [];
				$time = explode(',',$val);
				//查找所选日期的所有公司
				$where = "`start_time` = '".$time[0]."' and `end_time` = '".$time[1]."'";
				$list = model(GetTableModel('Week'))->where($where)->field('id,name,status,division_method,division_method_round,department,integral_accident,integral_complaint,integral_subtraction')->select();
				$list = collection($list)->toArray();
				if(empty($list)) continue;
				$excel = new PHPExcel();
				//判断属否存在数据
				$i = 0;
				foreach($list as $kk=>$vv){
					$i++;
					$excel->getProperties()
						->setCreator("gzy")
						->setLastModifiedBy("gzy")
						->setTitle($vv['department_text'])
						->setSubject("周记账表");
					  //从第几行开始
					   $line = 2;
					   $styleArray = array(
							 'font' => array(
									'size'  => 10,
									'name'  => 'Verdana'
							 ),
							  'borders' => array(
									'allborders' => array( //设置全部边框
										'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
									),

								),
					   );
					$worksheet = $excel->setActiveSheetIndex($kk);
					$excel->getActiveSheet()->mergeCells('A1:I1');//合并第一行的单元格
					$excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
					$excel->setActiveSheetIndex($kk)->setCellValue('A1', $vv['department_text'].$val.'记账');//标题
					$excel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);  
					$worksheet->setTitle($vv['department_text']);
					$sss = 0;
					foreach(ExcelWeekField(2) as $ks=>$vs){
						if($vs['type'] == 2) continue;
						$worksheet->setCellValueByColumnAndRow($sss, $line, $vs['name']);
						$excel->getActiveSheet()-> getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($sss))->setWidth($vs['width']);
						$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
						$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
						$sss++;
						
					}
					//查找此公司的所有天数
					$books_arr = TableListSqlQuery('Books','`extract_week` = '.$vv['id'].'');
					if(empty($books_arr)) continue;
					$balance = 0;
					foreach($books_arr as $index=>$item){
						//获取此天数的详情
						$item['Books_view'] = TableListSqlQuery('Books_view','`extract_week` = '.$vv['id'].' and `day` = '.$item['day'].'');
						$day = $item['day'] - 1;
						$day = date('Y-m-d',strtotime($time[0]." +".$day." day"));
						if(empty($item['Books_view'])) continue;
						foreach($item['Books_view'] as $k=>$v){
							$line++;
							$sss = 0;
							if($v['pay_type'] == 1){
								$balance =  $balance + $v['price'];
							}elseif($v['pay_type'] == 2){
								$balance =  $balance - $v['price'];
							}
							foreach(ExcelWeekField(2) as $ks=>$vs){
								if($vs['type'] == 2) continue;
								switch ($vs['key']) {
									 case 'date':
										$worksheet->setCellValueByColumnAndRow($sss, $line, $day);
										break;
									 case 'cost_id':
										$worksheet->setCellValueByColumnAndRow($sss, $line, !empty($v['cost_id']) && $v['pay_type'] == 2 ? TableField('Cost','name',$v['cost_id']) : '-');
										break;
									 case 'pay_type1':
										if($v['pay_type'] == 1){
											$worksheet->setCellValueByColumnAndRow($sss, $line,$v['price']);
										}else{
											$worksheet->setCellValueByColumnAndRow($sss, $line,'');
										}
										break;
									 case 'pay_type2':
										if($v['pay_type'] == 2){
											$worksheet->setCellValueByColumnAndRow($sss, $line,$v['price']);
										}else{
											$worksheet->setCellValueByColumnAndRow($sss, $line,'');
										}
										break;
									 case 'balance':
										$worksheet->setCellValueByColumnAndRow($sss, $line, $balance);
										break;
									default:
										$worksheet->setCellValueByColumnAndRow($sss, $line, $v[$vs['key']]);
										 break;
									}
								$worksheet->getStyleByColumnAndRow($sss,$line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
								$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
								$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
								//$worksheet->getColumnDimension($sss)->setWidth(50);;
								$sss++;
							}
						}
						unset($day);
					}
					$excel->createSheet();
					unset($worksheet);
				}
				if($i>0){
					
					//删除空的sheet
					$sheetIndex = $excel->getIndex($excel->getSheetByName('Worksheet')); 
					if($sheetIndex) $excel->removeSheetByIndex($sheetIndex);
					$title = $val;
					$objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
					$excelName = "uploads/excelbooks/日记账表" . $title . ".xlsx";
					$objWriter->save($excelName);
					$url[$ssss]['url'] = ''.request()->domain().'/'.$excelName.'';
					$ssss++;
				}
			}
		}
		return $url;
		
		
	}
}
if (!function_exists('ExcelWeekSales')) {
	/**
	 * 导出会销表
	 * @return array
	 * @author gzy
	 * @time 2018年9月28日 17:35:21
	 */
	function ExcelWeekSales($id = NULL,$type = NULL){
		if(empty($id)||empty($type)) return [];
		set_time_limit(0);
		$excel = new PHPExcel();
		$total = [];
		$a = 0;
		$list = [];
		$info = TableListSqlQuery('Sales'.$type,'season.`extract_week` = '.$id.'');
		//带队人员
		$userid = array_column(TableListSqlQuery('Field',"`extract_week` = '".$id."' and find_in_set('6',position)",'userid','hdyj_finance_extract_user'),'userid',null);
		$team_ls = GetExplode($userid,'Admin','username','userid');
		if($type == 'Analysis'){
			$arr['name'] = '提分宝典';
			$arr['display'] = 2;
		}else{
			$arr['name'] = '一轮书';
			$arr['display'] = 3;
		}
		//公司名称
		$department = model(GetTableModel('Week'))->where("id = '".$id."'")->field('start_time,end_time,department,status,division_method,division_method_round,integral_accident,integral_complaint,integral_subtraction')->find();
		$title = $department['department_text'].$arr['name'].'单周会销表';
		$title1 = $department['department_text'].$department['start_time'].','.$department['end_time'].$arr['name'].'单周会销表';
		$key_arr = array('season_time','address','province','city','area','lecturer_id','subject_id');
		foreach($info as $key=>$val){
			$arrs = [];
			foreach($key_arr as $as => $bs){
			   $list[$val['id']][$bs] = $val[$bs];
			   unset($val[$bs]);
			}
			$arrs['price'] = $val['price']??0;
			$arrs['num'] = $val['num']??0;
			$arrs['price_total'] = $val['price_total']??$val['price']*$val['num'];
			$list[$val['id']]['price'][] = $arrs;
		}
		
		if(empty($list)) return [];
		$excel->getProperties()
			->setCreator("gzy")
			->setLastModifiedBy("gzy")
			->setTitle($title)
			->setSubject($title);
	   //从第几行开始
	   $line = 2;
	   $styleArray = array(
			 'font' => array(
					'size'  => 10,
					'name'  => 'Verdana'
			 ),
			  'borders' => array(
					'allborders' => array( //设置全部边框
						'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
					),

				),
	   );
	
		$worksheet = $excel->setActiveSheetIndex($a);
					
		$excel->getActiveSheet()->mergeCells('A1:T1');//合并第一行的单元格
		$excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		
		$excel->setActiveSheetIndex($a)->setCellValue('A1',$title);//标题
		$excel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);  
		$sss = 0;
		foreach(ExcelWeekField(3) as $kk=>$vv){
			if($vv['display'] != $arr['display'] && $vv['display'] != 1) continue;
			$worksheet->setCellValueByColumnAndRow($sss, $line, $vv['name']);
			$excel->getActiveSheet()-> getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($sss))->setWidth($vv['width']);
			$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
			$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sss++;
		}
		
		$worksheet->setTitle($title);
		$mynum = 1;//序号
		foreach ($list as $index => $item) {
					
					$sss = 0;
					foreach(ExcelWeekField(3) as $kk=>$vv){
						if($vv['display'] != $arr['display'] && $vv['display'] != 1) continue;
						if($vv['type'] == 4){
							if($vv['key'] == 'POS'){
								$twonum = $line+1;
								if($arr['display'] == 2){
									$excel->getActiveSheet()->mergeCells('R3:R'.$twonum.'');//合并第一行的单元格
									$excel->getActiveSheet()->getStyle('R3:R'.$twonum.'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
									$excel->getActiveSheet()->getStyle('R3:R'.$twonum.'')->applyFromArray($styleArray);
								}else{
									$excel->getActiveSheet()->mergeCells('AC3:AC'.$twonum.'');//合并第一行的单元格
									$excel->getActiveSheet()->getStyle('AC3:AC'.$twonum.'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
									$excel->getActiveSheet()->getStyle('AC3:AC'.$twonum.'')->applyFromArray($styleArray);
									$excel->setActiveSheetIndex($a)->setCellValue('AC3','');
								}
								unset($twonum);
							}else{
								$onenum = $line+1;
								$twonum = $line+count($item['price']);
								$excel->getActiveSheet()->mergeCells(''.$vv['letter'].$onenum.':'.$vv['letter'].$twonum.'');//合并第一行的单元格
								$excel->getActiveSheet()->getStyle(''.$vv['letter'].$onenum.':'.$vv['letter'].$twonum.'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
								$excel->getActiveSheet()->getStyle(''.$vv['letter'].$onenum.':'.$vv['letter'].$twonum.'')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
								$excel->getActiveSheet()->getStyle(''.$vv['letter'].$onenum.':'.$vv['letter'].$twonum.'')->applyFromArray($styleArray);
								if($vv['key'] == 'mynum'){
									$excel->setActiveSheetIndex($a)->setCellValue(''.$vv['letter'].$onenum.'',$mynum);
								}elseif($vv['key'] == 'subject_id'){
									$excel->setActiveSheetIndex($a)->setCellValue(''.$vv['letter'].$onenum.'', TableField('Subject','name',$item[$vv['key']]));
								}elseif($vv['key'] == 'team_ls'){
									$excel->setActiveSheetIndex($a)->setCellValue(''.$vv['letter'].$onenum.'',$team_ls);
								}else{
									$excel->setActiveSheetIndex($a)->setCellValue(''.$vv['letter'].$onenum.'', $item[$vv['key']]);
								}
								unset($onenum,$twonum);
							}
							$excel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);  
						}else{
							$price_count = count($item['price']) - 1;
							foreach($item['price'] as $k=>$v){
								if(isset($vv['key'])){
									if($vv['key'] == 'num'){
										$line++;
										$price_line = $line;
									}
								}
								$price_line = $price_line ?? $line - ($price_count-$k);
								if($vv['type'] == 3){
									$worksheet->setCellValueByColumnAndRow($sss, $price_line, '');
								}else{
									if($vv['type'] == 2){
										$total[$vv['key']] = $total[$vv['key']]??0;
										$total[$vv['key']] += $v[$vv['key']];
									}
									$worksheet->setCellValueByColumnAndRow($sss, $price_line, $v[$vv['key']]);
								}
								$worksheet->getStyleByColumnAndRow($sss,$price_line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
								$worksheet->getCellByColumnAndRow($sss, $price_line)->getStyle()->applyFromArray($styleArray);
								$worksheet->getCellByColumnAndRow($sss, $price_line)->getStyle($sss, $price_line)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
								$worksheet->getCellByColumnAndRow($sss, $price_line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
								unset($price_line);
							}
						
						}
						//$worksheet->getColumnDimension($sss)->setWidth(50);;
						$sss++;
					}
				$mynum++;
			}
		$line = $line+1;
		//$point_total = array_sum(array_map(function($val){return $val['point_total'];}, $list));
		//$point_total = array_sum(array_map(function($val){return $val['point_total'];}, $list));
		//合计
		$sss = 0;
		foreach(ExcelWeekField(3) as $kk=>$vv){
			if($vv['display'] != $arr['display'] && $vv['display'] != 1) continue;
			$worksheet->setCellValueByColumnAndRow($sss, $line, $total[$vv['key']??'']??'');
			$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
			$worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$sss++;
		}
		$excel->getActiveSheet()->mergeCells('A'.$line.':E'.$line.'');//合并第一行的单元格
		$excel->getActiveSheet()->getStyle('A'.$line.'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$excel->setActiveSheetIndex($a)->setCellValue('A'.$line.'', '合计');//标题
		//print_R($total);die;
		$excel->createSheet();
		//删除空的sheet
		$sheetIndex = $excel->getIndex($excel->getSheetByName('Worksheet')); 
		if($sheetIndex) $excel->removeSheetByIndex($sheetIndex);
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="' . $title1 . '.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');
		// If you're serving to IE over SSL, then the following may be needed
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
		header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header('Pragma: public'); // HTTP/1.0
		$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
		$objWriter->save('php://output');
		return;
	}
}
if (!function_exists('mergeCells')) {
	/**
	 * excel字段 
	 * @return array
	 * @author gzy
	 * @time 2018年10月8日 13:35:21
	 */
	function mergeCells($type,$l = 'A'){
		switch ($type) {
		 case 0:
			if($l == 'A'){
			 $td =  'A';
			}else{
			 $td =  'B';
			}	
			break;
		 case 1:
			if($l == 'A'){
			 $td =  'C';
			}else{
			 $td =  'D';
			}	
			break;
		 case 2:
			if($l == 'A'){
			 $td =  'E';
			}else{
			 $td =  'F';
			}	
			break;
		 case 3:
			if($l == 'A'){
			 $td =  'G';
			}else{
			 $td =  'G';
			}	
			break;
		}
		return $td;
	}
}
if (!function_exists('ExcelWeekField')) {
	/**
	 * excel字段 
	 * @return array   name=名称 key=字段名称 width=宽  type 如果=1则代表不需要计算，如果=2则代表需要计算 =3代表为空 = 4为合并
	  display=1 代表所有模块显示 =2 代表在周提成显示 =3代表在月提成显示 
	 * @author gzy
	 * @time 2018年10月8日 13:35:21
	 */
	function ExcelWeekField($type = 1){
		$arr1 = [
				 [ 'name'=>'序号',
				   'key'=>'mynum',
				   'width'=>5,
				   'type'=>1,
				   'display'=>1,
				 ],
				 [ 'name'=>'姓名',
				   'key'=>'username_text',
				   'width'=>10,
					'type'=>1,
					'display'=>1,
				 ],
				 [ 'name'=>'身份证号',
				   'key'=>'idnumber_text',
				   'width'=>20,
				    'type'=>1,
					'display'=>1,
				 ],
				
				 [ 'name'=>'提分版税',
				   'key'=>'point_total',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,
				 ],
				 [ 'name'=>'图书版税',
				   'key'=>'books_total',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,
				 ],
				 [ 'name'=>'提分+图书版税',
				   'key'=>'point_books',
				   'width'=>10,
				   'type'=>2,
				   'display'=>2,
				 ],
				 [ 'name'=>'奖励',
				   'key'=>'reward',
				   'width'=>10,
				   'type'=>2,
					'display'=>2,
				 ],
				/* [ 'name'=>'暂扣百分之30',
				   'key'=>'withhold',
				   'width'=>10,
				   'type'=>2,
					'display'=>2,
				 ],
				 [ 'name'=>'应发版税',
				   'key'=>'answer_total',
				   'width'=>10,
				   'type'=>2,
					'display'=>2,
				 ],*/
				 [ 'name'=>'签约版税',
				   'key'=>'contract_total',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,
				 ],
				 [ 'name'=>'股份版税',
				   'key'=>'shares_total',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,
				 ],
				 [ 'name'=>'参会版税',
				   'key'=>'admission_fee',
				   'width'=>10,
				   'type'=>2,
				   'display'=>1,  
				 ],

				 [ 'name'=>'版税合计',
				   'key'=>'week_total',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,  
				 ],
				 [ 'name'=>'实扣税金',
				   'key'=>'tax_total',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,  
				 ],
				 [ 'name'=>'应扣税金',
				   'key'=>'answer_tax',
				   'width'=>10,
				   'type'=>2,
					'display'=>3,  
				 ],
				 [ 'name'=>'欠缴税金',
				   'key'=>'tax_owe',
				   'width'=>10,
				   'type'=>2,
					'display'=>2, 
				 ],
				 [ 'name'=>'欠缴税金',
				   'key'=>'owe_tax',
				   'width'=>10,
				   'type'=>2,
				   'display'=>3, 
				 ],
				 [ 'name'=>'多扣税金',
				   'key'=>'repair_tax',
				   'width'=>10,
				   'type'=>2,
				   'display'=>3, 
				 ],
				 [ 'name'=>'无票金额',
				   'key'=>'no_ticket_total',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,  
				 ],
				 [ 'name'=>'已缴无票',
				   'key'=>'no_ticket_noowe',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,  
				 ],
				 [ 'name'=>'欠扣无票',
				   'key'=>'no_ticket_owe',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,  
				 ],
				 [ 'name'=>'实发版税',
				   'key'=>'real_hair',
				   'width'=>10,
				   'type'=>2,
					'display'=>1,  
				 ],
				 [ 'name'=>'应发版税',
				   'key'=>'answer_hair',
				   'width'=>10,
				   'type'=>2,
					'display'=>3,  
				 ],
				 [ 'name'=>'卡号',
				   'key'=>'cardnumber_text',
				   'width'=>20,
					'type'=>1,
					'display'=>1, 
				 ],
				 [ 'name'=>'手机号',
				   'key'=>'mobile_text',
				   'width'=>15,
					'type'=>1,
					 'display'=>1, 

				 ],
				 [ 'name'=>'日期',
				   'key'=>'datemonth',
				   'width'=>15,
					'type'=>1,
					 'display'=>3, 

				 ],
				];
		$arr2 = [
				[ 'name'=>'日期',
				   'key'=>'date',
				   'width'=>20,
				   'type'=>1,
				 ],
				 [ 'name'=>'凭证单号',
				   'key'=>'number',
				   'width'=>20,
				   'type'=>1,
				 ],
				 [ 'name'=>'费用项目',
				   'key'=>'cost_id',
				   'width'=>30,
					'type'=>1,
				 ],
				/* [ 'name'=>'收支类型',
				   'key'=>'pay_type',
				   'width'=>8,
				    'type'=>1,
				 ],*/
				 [ 'name'=>'收入',
				   'key'=>'pay_type1',
				   'width'=>15,
				    'type'=>1,
				 ],
				 [ 'name'=>'支出',
				   'key'=>'pay_type2',
				   'width'=>15,
				    'type'=>1,
				 ],
				/*
				 [ 'name'=>'价钱',
				   'key'=>'price',
				   'width'=>15,
				   'type'=>1,
				 ],*/
				 [ 'name'=>'费用摘要',
				   'key'=>'abstract',
				   'width'=>30,
				   'type'=>1,
					
				 ],
				 [ 'name'=>'经办人签字',
				   'key'=>'sign',
				   'width'=>10,
				   'type'=>1,
				 ],
				 [ 'name'=>'备注',
				   'key'=>'desc',
				   'width'=>10,
				   'type'=>1,
				 ],
			
				 [ 'name'=>'收入',
				   'key'=>'income',
				   'width'=>15,
				   'type'=>2,
				 ],
				 [ 'name'=>'支出',
				   'key'=>'expenditure',
				   'width'=>15,
				   'type'=>2,
				 ],
				 [ 'name'=>'余额',
				   'key'=>'balance',
				   'width'=>15,
				   'type'=>1,
				 ],
				];
		 $arr3 = [
				 [ 'name'=>'序号',
				   'key'=>'mynum',
				   'width'=>5,
				   'type'=>4,
				    'display'=>1,
					'letter'=>'A',
				 ],
				 [ 'name'=>'地区',
				   'key'=>'address',
				   'width'=>20,
				   'type'=>4,
			       'display'=>1,
			 'letter'=>'B',
				 ],
				 [ 'name'=>'场次',
				   'key'=>'season_time',
				   'width'=>30,
					'type'=>4,
			       'display'=>1,
			 'letter'=>'C',
				 ],
				 [ 'name'=>'带队',
				   'key'=>'team_ls',
				   'width'=>15,
				   'type'=>4,
			       'display'=>1,
			       'letter'=>'D',
				 ],
				 [ 'name'=>'科目',
				   'key'=>'subject_id',
				   'width'=>15,
				   'type'=>4,
			       'display'=>1,
					'letter'=>'E',
				 ],
				 [ 'name'=>'销售总数',
				   'key'=>'num',
				   'width'=>15,
				   'type'=>2,
			       'display'=>1,
				 ],
			 	 [ 'name'=>'单价',
				   'key'=>'price',
				   'width'=>15,
				   'type'=>1,
			       'display'=>1,
				 ],
			 	 [ 'name'=>'总金额',
				   'key'=>'price_total',
				   'width'=>15,
				   'type'=>2,
			       'display'=>1,
				 ],
				['name'=>'刷卡+现金补余数量','width'=>15,'type'=>3,'display'=>1],
				['name'=>'刷卡明细','width'=>15,'type'=>3,'display'=>1],
				['name'=>'刷卡金额','width'=>15,'type'=>3,'display'=>1],
				['name'=>'现金补余金额','width'=>15,'type'=>3,'display'=>1],
				['name'=>'刷卡及现金补余合计','width'=>15,'type'=>3,'display'=>1],
				['name'=>'现金数量','width'=>15,'type'=>3,'display'=>1],
				['name'=>'单价','width'=>15,'type'=>3,'display'=>1],
				['name'=>'现金合计','width'=>15,'type'=>3,'display'=>1],
				['name'=>'会场销售总计','width'=>15,'type'=>3,'display'=>2],
				['name'=>'总金额','width'=>15,'type'=>3,'display'=>3],
				['name'=>'语文','width'=>5,'type'=>3,'display'=>3],
				['name'=>'英语','width'=>5,'type'=>3,'display'=>3],
				['name'=>'文数','width'=>5,'type'=>3,'display'=>3],
				['name'=>'数学','width'=>5,'type'=>3,'display'=>3],
				['name'=>'物理','width'=>5,'type'=>3,'display'=>3],
				['name'=>'化学','width'=>5,'type'=>3,'display'=>3],
				['name'=>'生物','width'=>5,'type'=>3,'display'=>3],
				['name'=>'政治','width'=>5,'type'=>3,'display'=>3],
				['name'=>'地理','width'=>5,'type'=>3,'display'=>3],
				['name'=>'历史','width'=>5,'type'=>3,'display'=>3],
				['name'=>'合计','width'=>15,'type'=>3,'display'=>3],
				['name'=>'POS终端号' , 'key'=>'POS','width'=>15,'type'=>4,'display'=>1],
				
				];
		if($type == 1){
			return $arr1;
		}elseif($type == 2){
			return $arr2;
		}else{
			return $arr3;
		}
	}
}
if (!function_exists('InstallNoteTasks')) {
    /**
     * 插入任务审核记录
     * @author gzy
     * @time 2019年1月8日 15:00:00
     */
    function InstallNoteTasks($row =[],$check = 0,$desc = NUll){
            $note = [];
            $note['task_id'] = $row->task_id;
            $note['ob_id'] = $row->id;
            $note['status'] = $row->status;
            $note['check'] = $check;
            $note['desc'] = $desc;
            $note['publish'] =  \think\Session::get('admin')['userid'];
            model(GetTableModel('Note'))->save($note);

            return true;
      }
}
if (!function_exists('InstallSchoolTask')) {
    /**
     * 插入学校 任务相关
     * @author gzy
     * @time 2019年1月8日 16:00:00
     */
    function InstallSchoolTask($id = NULL,$row =[]){
          if(empty($id) || empty($row)) return false;
            $school = [];
            $school['extract_week'] = $id;
            $school['publish']    = \think\Session::get('admin')['userid'];
            $school['z_publish']  = \think\Session::get('admin')['userid'];
            $school['season_id'] = $row->season_id;
            $school['school_id'] = $row->school_id;
            $school['reg_level'] = $row->reg_level;
            $school['level'] = $row->level;
            $school['ranking_level'] = $row->ranking_level;
            $school['book_num'] = $row->book_num;
            $school['book_price'] = $row->book_price;
            $school['coming_num'] = $row->school_num;
            $school['people_num'] = $row->people_num;
            $school['gift_books'] = $row->issued;
            $data = [
                'type1'=>$row->salesinfo,
                'type2'=>json_encode(array_column(ObjectArray(json_decode($row->userinfo)),'proportion','userid'))
             ];
            $model = model(GetTableModel('School'));
            if($result = $model->save($school)){
                model(GetTableModel('School_data'))->saveAll(HandleSchool($model->id,$data));
            }
            return true;
      }
}
if (!function_exists('GetStatusTasks')) {
    /**
     * 获取任务状态 去更改
     * @author gzy
     * @time 2019年1月8日 15:00:00
       'Task.Status'  =>  '任务状态',
    'Task.Status 1'  =>  '待提交',
    'Task.Status 2'  =>  '审核失败',
    'Task.Status 3'  =>  '合跑人待审核',
    'Task.Status 4'  =>  '会务待审核',
    'Task.Status 5'  =>  '分公司财务待审核',
    'Task.Status 6'  =>  '分公司负责人待审核',
    'Task.Status 7'  =>  '客户管理部待审核',
    'Task.Status 8'  =>  '客户管理部审核失败',
    'Task.Status 9'  =>  '审核成功',
    
        合跑人审核           tasks/task/review_1           
            会务审核                tasks/task/review_2               
            分公司财务审核     tasks/task/review_3               
            分公司负责人审核        tasks/task/review_4               
            客户管理部审核     tasks/task/review_5
     */
    function GetStatusTasks($status = null,$check = null){
        if(empty($status) || empty($check)) return 0;
            $info = $status.'-'.$check;
            switch ($info) {
                 case '1-1':
                 case '2-1':
                 case '3-1':
                 case '4-1':
                    $check_status = $status+3;
                    break;  
                 case '5-1':
                    $check_status = 9;
                    break;   
                 case '1-2':
                 case '2-2':
                 case '3-2':
                    $check_status = 2;
                    break;  
                case '4-2':
                case '5-2':
                    $check_status = 8;
                    break; 
                default:
                    $check_status = 0;
                    break;
            }
         return $check_status;
      }
}
if (!function_exists('GetRoleTasks')) {
    /**
     * 获取任务权限
     * @author gzy
     * @time 2019年1月7日 15:00:00
         'Task.Status'  =>  '任务状态',
    'Task.Status 1'  =>  '待提交',
    'Task.Status 2'  =>  '审核失败',
    'Task.Status 3'  =>  '合跑人待审核',
    'Task.Status 4'  =>  '会务待审核',
    'Task.Status 5'  =>  '分公司财务待审核',
    'Task.Status 6'  =>  '分公司负责人待审核',
    'Task.Status 7'  =>  '客户管理部待审核',
    'Task.Status 8'  =>  '客户管理部审核失败',
    'Task.Status 9'  =>  '审核成功',

     */
    function GetRoleTasks(){
        $pid = TableField('AuthRule','id','tasks/task/review','name');
        $data['AuthInfo'] = TableList('AuthRule',$pid,'pid',[],'weigh','desc');
        $group = implode(',',\think\Session::get('admin')['group_id']);
        $info = [];
        foreach($data['AuthInfo'] as $key=>$val){
            $true = GetCheck($val['name'],$group);
            if($true){
                switch ($val['name']) {
                //合跑人审核
                 case 'tasks/task/review_1':
                    $info[] = 3;
                    break;  
                //会务审核
                 case 'tasks/task/review_2':
                    $info[] = 4;
                    break; 
               //分公司财务审核    
                case 'tasks/task/review_3':
                    $info[] = 5;
                    $info[] = 8;
                    break;
                //分公司负责人审核
                case 'tasks/task/review_4':
                    $info[] = 6;
                    break;
                //客户管理部审核
               case 'tasks/task/review_5':
                    $info[] = 7;
                    break;      
           /*     //客户管理部审核
               case 'tasks/task/check':
                    $info[] = 1;
                    $info[] = 2;
                    break;*/
                default:
                    break;
                }
            }
         }
         return $info;
      }
}
if (!function_exists('GetRoleFinance')) {
	/**
	 * 财务管理权限 
	 * @return array
	 * @author gzy
	 * @time 2018年9月10日 10:00:21
   return [0=>'草稿',1=>'初审中',-1=>'初审驳回',2=>'初审通过',3=>'终审中',-2=>'终审驳回',4=>'终审完成'];
	 */
	function GetRoleFinance($alias = null){
    //$roles = GetRows();
    //默认就给全部
		$roles = 1;
  //  $where = ' `delete_status` = 1 and `status` not in(-1,0,1,2) ';
		$where = ' `delete_status` = 1 ';
		$role = null;
		switch ($roles) {
  			//所有
  			  case '1':
  				$role = 2;
    				break;
    			//部门
    			 case '2':
           $department =  check_Department(\think\Session::get('admin')['department']);
    				$top = ValueExists(GetBaseInfo('Dept'),$department);
    				if($department){
    					// $topArr = [];
    					// foreach($top as $val){
    					// 	//$topArr[] = TableListSqlQuery('Field'," `parentid` = '".$val."' ",'id','hdyj_auth_department');
    					// }
    					// $topArr = array_reduce($topArr, 'array_merge', array());
    					// $topArr = implode(',',array_column($topArr,'id'));
              $where .=  "and find_in_set('".$department."',department)>0";
    				}
    				$role = $department;
           break;
    			 //个人
    			 case '3':
              $userid = \think\Session::get('admin')['userid'];
              $where .= " and `publish` = '".$userid."'";
    			    break;
           default:
              break;
        }
        
		return ['where'=>$where,'role'=>$role];
	}
}

if (!function_exists('GetWeekModel')) {
	 /**
     * 获取周数据模块信息
     * @return array
	 * @author gzy
	 * @date   2018年8月28日 16:30:00
     */
    function GetWeekModel($row = []) {
	
		$arr = [
			'Score'=>[
				'Books'=>[
					'index'=>'finance/extract/week/books_index',
					'add'=>'finance/extract/week/books_add',
					'edit'=>'finance/extract/week/books_edit',
          'delete'=>'finance/extract/week/books_delete',
					'WeChat'=>['true'=>1,'img'=>'/plan/img/list17.png'],
				 ],
				'User'=>[
					'index'=>'finance/extract/week/user_index',
					'add'=>'finance/extract/week/user_add',
					'edit'=>'finance/extract/week/user_edit',
          'delete'=>'finance/extract/week/user_delete',
					'task'=>'finance/extract/week/user_task',
          'WeChat'=>['true'=>1,'img'=>'/plan/img/list20.png'],
				 ],
				'Season'=>[
					'index'=>'finance/extract/week/season_index',
					'add'=>'finance/extract/week/season_add',
					'edit'=>'finance/extract/week/season_edit',
					'delete'=>'finance/extract/week/season_delete',
          'WeChat'=>['true'=>1,'img'=>'/plan/img/list21.png"'],
				 ],
				'School'=>[
					'index'=>'finance/extract/week/school_index',
					'add'=>'finance/extract/week/school_add',
					'edit'=>'finance/extract/week/school_edit',
					'delete'=>'finance/extract/week/school_delete',
          'WeChat'=>['true'=>0,'img'=>'list17.png'],
				 ],
				'Analysis'=>[
					'index'=>'finance/extract/week/analysis_index',
					'export'=>'finance/extract/week/analysis_export',
          'WeChat'=>['true'=>0,'img'=>'list17.png'],
				 ],
         'Check'=>[
            'index'=>'finance/extract/week/check',
            'WeChat'=>['true'=>0]
         ],
			],
		   'Round_book'=>[
				'User'=>[
					'index'=>'finance/extract/week/user_index',
					'edit'=>'finance/extract/week/user_edit',
				 ],
				'Venue_sales'=>[
					'index'=>'finance/extract/week/sales_index',
					'edit'=>'finance/extract/week/sales_edit',
				 ],
				'Round_analysis'=>[
					'index'=>'finance/extract/week/round_analysis_index',
					'export'=>'finance/extract/week/round_analysis_export',
				 ],
			],
		   
		];
		foreach($arr as $key=> &$val){
			if(AdminAuth('finance/extract/week/'.$key)){
				foreach($val as $k=>&$v){
					if(AdminAuth('finance/extract/week/'.$k) && AdminAuth(isset($v['index']) ? $v['index']:'')){
						  if(!AdminAuth(isset($v['add']) ? $v['add']:'') || $row['status'] >= 3)unset($v['add']);
            if(!AdminAuth(isset($v['edit']) ? $v['edit']:'')||  $row['status'] >= 3) unset($v['edit']);
            if(!AdminAuth(isset($v['delete'])? $v['delete']:'')||  $row['status'] >= 3) unset($v['delete']);
						if(!AdminAuth(isset($v['export']) ? $v['export']:'')) unset($v['export']);
					}else{
						unset($val[$k]);
					}
				}
			}else{
				unset($arr[$key]);
			}
		}
        return $arr;
    }
}
if (!function_exists('CheckeWeekStatus')) {
     /**
     * 查询周状态是否支持修改 
     * @return array
     * @param  int    $id  周id
     * @author gzy
     */
    function CheckeWeekStatus($id = NULL) {
        $status = TableField('Week','status',$id,'id');
        if($status >= 3) return ['status'=>false,'msg'=>'此周无法操作'];
        return  ['status'=>true];
    }
}
if (!function_exists('GenerateWeek')) {
     /**
     * 生成周数据 
     * @return array
     * @param  int    $id  周id
     * @author gzy
     * @date   2018年8月28日 16:30:00
     * @update 2019年12月13日  
     */
    function GenerateWeek($id = NULL) {
        $userarr = [];
        $userarr  = GenerateWeekUser($id);
        $lecturer_id = '';
         //最近一周的讲师
       if($userarr['department']){ 
          $week_info = TableList('Week',$userarr['department'],'department'," and `status` not in(-1,0,1) and `lecturer_id` <> ''",'start_time','desc',2);
          if($week_info) $lecturer_id =$week_info[0]['lecturer_id'];
        }
        //周成员
       if($userarr['user']) model(GetTableModel('User'))->saveAll($userarr['user']);
        return [1,$lecturer_id];
    }
}
if (!function_exists('GenerateWeekUser')) {
   /**
     * 生成周数据-成员
     * @param  int    $id  周id
     * @return array
   * @author gzy
   * @date   2018年9月3日 15:30:00
     */
    function GenerateWeekUser($id = NULL) {
        if(empty($id)) return [];
        $arr = [];
        if($department = TableField('Week','department',$id)){
            $dept = check_DepartmentChild($department);
            $where = " find_in_set('".$department."',department) ";
            foreach ($dept as $key => $value) {
              if($value != $department){
                 $where .=" or find_in_set('".$value."',department) ";
              }
            }
            $arr = TableListSqlQuery('Admin',$where,'userid');
         }
         $additional =[];
         $additional['extract_week'] = $id;
         foreach($arr as &$val){
            if($userid = TableField('User','id',$val['userid'],'userid',$additional)){
                $val['id'] = $userid;
                unset($val['position']);
            }else{
              $val['extract_week'] = $id;
              $val['status'] = 1;
              $val['desc'] = '自动生成数据';
              $val['publish'] = \think\Session::get('admin')['userid'];
            }
          $val['z_publish'] = \think\Session::get('admin')['userid'];
        }
        //print_R($arr);die;
        return ['user'=>$arr,'department'=>$department];
    }
}
if (!function_exists('GenerateGroup')) {
	 /**
     * 生成分组  无用
     * @return array
	 * @author gzy
	 * @date   2018年12月20日 20:30:00
     */
    function GenerateGroup($arr = [],$row = []) {
		//TableList('week',$row['start_time'],'start_time','',$sort = NULL,$order = NULL) {
       $a = [];
       foreach ($arr as $key => $value) {
           foreach ($value as $k => $v) {
              $a[] = $v;
           }
       }
       $aa = implode($a, ',');
       //$sql = " select * from hdyj_finance_extract_week where `start_time` = '".$row['start_time']."' and `department` not in (".$a.")";
       $sql = " select * from hdyj_finance_extract_week where `start_time` = '".$row['start_time']."' and `department` not in (".$aa.")";
       $sql2 = " select * from hdyj_finance_extract_week where `start_time` = '".$row['start_time']."' and `department` in (".$aa.")";
       $ins_arr = [];
       $i = 0;
       if($info = array_column(\think\Db::query($sql),'id','department')){
            
            foreach($info as $ks=>$vs){
                $ins_arr[$i]['id'] = $vs;
                $ins_arr[$i]['delete_status'] = 2;
                $i++;
            }            
       }
       unset($info);
       $info = array_column(\think\Db::query($sql2),'id','department');
        foreach($a as $kk=>$vv){
            if(isset($info[$vv])){
                $ins_arr[$i]['id'] = $info[$vv];
                $ins_arr[$i]['delete_status'] = 1;
            }else{
                $ins_arr[$i] = $row;
                $ins_arr[$i]['department'] = $vv;
            }
            $i++;
        }            
       $saveweek = 0;
      
       if(!empty($ins_arr)) $saveweek = model(GetTableModel('Week'))->saveAll($ins_arr);
       $userarr = [];
       //生成周数据-成员
       foreach ($saveweek as $ke => $val) {
          $userarr =  array_merge($userarr,GenerateWeekUser($val['id']));
       }
       model(GetTableModel('User'))->saveAll($userarr);
       return $saveweek;
    }
}
if (!function_exists('GenerateWeekUserTask')) {
     /**
     * 生成周数据-成员任务 无用
     * @param  int    $id  周id
     * @return array
     * @author gzy
     * @date   2018年12月21日 14:30:00
     */
    function GenerateWeekUserTask($id = NULL,$arr=[]) {
        if(empty($id)) return [];
        $info = array_column(TableListSqlQuery('Field',"`extract_week` = '".$id."' and  ( find_in_set( '4', position ) OR find_in_set( '5', position ) OR find_in_set( '20', position ) )",'userid,position','hdyj_finance_extract_user'),'position','userid');
        //外联任务
        $otreach_info = array_column(TableListSqlQuery('Field',"`extract_week` = ".$id." and type = 1  ",'id,userid,type,delete_status','hdyj_finance_extract_task'),null,'userid');  

        //图书任务
        $books_info = array_column(TableListSqlQuery('Field',"`extract_week` = ".$id." and type = 2  ",'id,userid,type,delete_status','hdyj_finance_extract_task'),null,'userid');

        $ins_arr =[];
        $i = 0;
        foreach($info as $key=>$val){
            $a = 0;$b = 0;$aid = 0;$bid = 0;
            if(isset($otreach_info[$key])){
                if(ValueExists('4',$val) || ValueExists('5',$val) ){
                    if($otreach_info[$key]['delete_status'] == 2){
                        $a = 1;
                        $aid = $otreach_info[$key]['id'];
                    }
                }else{
                    $aid = $otreach_info[$key]['id'];
                    $a = 2;
                }
            }else if(ValueExists('4',$val) || ValueExists('5',$val) ){
                $a = 1;
            }
            if(isset($books_info[$key])){
                if(ValueExists('20',$val) ){
                    if($books_info[$key]['delete_status'] == 2){
                        $b = 1;
                        $bid = $books_info[$key]['id'];
                    }
                }else{
                    $b = 2;
                    $bid = $books_info[$key]['id'];
                }
            }else if(ValueExists('20',$val)){
                $b = 1;
            }
            if($a){
                if($aid) $ins_arr[$i]['id'] = $aid;
                $ins_arr[$i]['userid'] = $key;
                $ins_arr[$i]['extract_week'] = $id;
                $ins_arr[$i]['type'] = 1;
                $ins_arr[$i]['delete_status'] = $a;
                $ins_arr[$i]['name'] = $arr['start_time'].'-'.$arr['end_time'].'外联任务';
                $ins_arr[$i]['publish'] = \think\Session::get('admin')['userid'];
                $ins_arr[$i]['z_publish'] = \think\Session::get('admin')['userid'];
                $i++;
            } 
            if($b){
                if($bid) $ins_arr[$i]['id'] = $bid;
                $ins_arr[$i]['userid'] = $key;
                $ins_arr[$i]['extract_week'] = $id;
                $ins_arr[$i]['type'] = 2;
                $ins_arr[$i]['delete_status'] = $b;
                $ins_arr[$i]['name'] = $arr['start_time'].'-'.$arr['end_time'].'图书任务';
                $ins_arr[$i]['publish'] = \think\Session::get('admin')['userid'];
                $ins_arr[$i]['z_publish'] = \think\Session::get('admin')['userid'];
                $i++;
            }
            
        }
       model(GetTableModel('Task'))->saveAll($ins_arr);
       return true;
    }
}

if (!function_exists('HandleRound')) {
	 /**
     * 处理一轮书信息
     * @param  int    $type  类型
     * @param  int    $additional  附加值
     * @return array
	 * @author gzy
	 * @date   2018年11月8日 14:15:00
     */
    function HandleRound($id = '',$data = []) {
		if(empty($id)  || empty($data)) return false;
		$arr = [];
		foreach($data as $key=>$val){
			if(!empty($data[$key])){
				$i = 0;
				foreach(ObjectArray(json_decode($data[$key])) as $k=>$v){
					$vv = [];
					if($key == 'type'){
						$vv['sales_type'] = $v['sales_type'];
						$vv['pricing_type'] = $v['pricing_type'];
						if(isset($v['pricing_price'])){
							$vv['pricing_price'] = $v['pricing_price'];
						}else{
							$vv['pricing_price'] = $v['pricing_price'.$v['pricing_type'].''];
						}
                        if($vv['pricing_type'] == 2){
                            $vv['data'] = $v['data'];
                        }
						$vv['sales_price'] = $v['sales_price'];
						$vv['pricing_num'] = $v['pricing_num'];
						$vv['round_num'] = $v['round_num'];
						$vv['desc'] = $v['desc'];
					}
					$vv['publish']  = \think\Session::get('admin')['userid'];
					$vv['z_publish']  = \think\Session::get('admin')['userid'];
					$vv['season_id'] = $id;
					$vv['weigh'] = $i;
					$arr[] = $vv;
					unset($vv);
					$i++;
				}
			}
		}
        return $arr;
    }
}
if (!function_exists('HandleSchool')) {
	 /**
     * 处理学校信息
     * @param  int    $type  类型
     * @param  int    $additional  附加值
     * @return array
	 * @author gzy
	 * @date   2018年8月28日 16:30:00
     */
    function HandleSchool($id = '',$data = [],$school_id = null) {
		if(empty($id)  || empty($data)) return false;
		$arr = [];
		foreach($data as $key=>$val){
			if(!empty($data[$key])){
				$i = 0;
				foreach(json_decode($data[$key]) as $k=>$v){
					$vv = [];
					if($key == 'type1'){
						$vv['type'] = 2;
						$vv['price'] = $k;
						$vv['num'] = $v;
					}else{
						if(isset($v->key)){
							$vv['type'] = 1;
							$vv['userid'] = $v->key;
							$vv['proportion'] = $v->value;
						}else{
							$vv['type'] = 1;
							$vv['userid'] = $k;
							$vv['proportion'] = $v;
						}
					}
					$vv['extract_school'] = $id;
					$vv['weigh'] = $i;
					$arr[] = $vv;
					unset($vv);
					$i++;
				}
			}
		}
        if($school_id){
            $UserInfo = TableList('School_data','1','delete_status',['extract_school'=>37,'type'=>1],'weigh','asc');
            $UserInfo = array_map(function($vss) use ($id){
                return [
                    'extract_school'=>$id,
                    'type'=>$vss['type'],
                    'extract_user'=>$vss['extract_user'],
                    'userid'=>$vss['userid'],
                    'proportion'=>$vss['proportion'],
                    'price'=>$vss['price'],
                    'num'=>$vss['num'],
                    'delete_status'=>$vss['delete_status'],
                    'weigh'=>$vss['weigh'],
                ];
            }, $UserInfo);
            $arr = array_merge($arr,$UserInfo);
        }
       
        return $arr;
    }
}
if (!function_exists('GetBookBalance')) {
	 /**
     * 获取日记账余额
     * @param  int    $id           周id
     * @param  int    $day          第几天
     * @param  int    $income       当天收入
     * @param  int    $expenditure  当天支出
     * @return array
	 * @author gzy
	 * @date   2018年9月2日 13:30:00
     */
  function  GetBookBalance($id = NULL,$day = 1){
		$arr = [ 
			'1'=>'1',
			'2'=>'1,2',
			'3'=>'1,2,3',
			'4'=>'1,2,3,4',
			'5'=>'1,2,3,4,5',
			'6'=>'1,2,3,4,5,6',
			'7'=>'1,2,3,4,5,6,7',
		];
		$info = TableListSqlQuery('Books','books.`extract_week` = '.$id.' and books.`day` in('.$arr[$day].')');
		$balance = 0;
		foreach($info as $key=>$val){
			$balance = $balance + $val['income'] - $val['expenditure'];	
		}
		return Rounding($balance);
	}
}
if (!function_exists('GetBaseInfo')) {
	 /**
     * 获取基础信息
     * @param  int    $table  默认值 
     * @return array
	 * @author gzy
	 * @date   2018年8月25日 16:30:00
     */
    function GetBaseInfo($table) {
		switch ($table) {
			//销售价格
			 case 'SalesPrice':
				$info = [
							'SalesPrice_1'=>2986,
							'SalesPrice_2'=>3686,
							'SalesPrice_3'=>3974,
							'SalesPrice_4'=>4674,
							'SalesPrice_5'=>4000,
						];
				break;
			//销售价格
			 case 'SalesPrice2':
				$info = [
							2986=>0,
							3686=>0,
							3974=>0,
							4674=>0,
						];
				break;
			//外联单场提成标准
			 case 'OutreachExtract':
					$info = [
							//标准套数 10 
							'Standard10'=>10,
							//标准套数
							'Standard'=>20,
							//小于标准的价格
							'Standard_lt'=>8,
							//大于等于标准的价格
							'Standard_egt'=>160,
							//小于10的价钱
							'Standard10_lt'=>80,
						];
                break;
			//管理分成标准
			 case 'ManageExtract':
					$info = [
							//标准单套价钱
							'StandardPrice'=>900,
							//小于标准的数据
							'StandardPrice_lt'=>[
								//价钱
								'price'=>150,
								//经理分成
								'ExtractHis'=>80,
								//副经理分成
								'ExtractDeputyHis'=>20,
							],
							//大于等于标准的数据
							'StandardPrice_egt'=>[
								//价钱
								'price'=>100,
								//经理分成
								'ExtractHis'=>90,
								//副经理分成
								'ExtractDeputyHis'=>10,
							],
						];
                break;
		   //无票税率 百分比
			case 'NoTicketRate':
				$info = [
							//固定比例 百分之25
							'Rate'=>25,
							//总经理
							'His'=>40,
							//副总经理
							'DeputyHis'=>8,
							//外联
							'Outreach'=>42,
							//财务
							'Finance'=>2.8,
							//会务
							'Meeting'=>4.7,
							//客服
							'Service'=>2.5,
						];
                break;
		   //税率
			case 'Tax':
				$info = [
							//标准价钱
							'Price'=>4000,
							//税率
							'Rate'=>14,
							//小于标准的数据
							'Price_lt'=>[
								//价钱
								'Price'=>800,
							],
							//大于等于标准的数据
							'Price_egt'=>[
								//百分比
								'His'=>20,
							],
						];
                break;
			//公共信息
			case 'Public':
				$info = [
							//手边题本价格
							'BookPrice'=>50,
							//每场套数 计算管理提成标准用
							'EachSet'=>30,
							//会务提成价格
							'MeetingPrice'=>20,
							//客服提成价格
							'ServicePrice'=>8,
							//财务提成价格
							'FinancePrice'=>8,
							//股份单价 没用到
							'SharesPrice'=>100,
							//版税股份单价 没用到
							'Unit_price'=>2,
							//交通补助
							'Traffic_subsidy'=>200,
							//税率
							'TaxSet'=>11.2,
						];
				 break;
			//模块信息
			case 'Model':
				$info = [
							'Score'=>'提分管理',
							'Round_book'=>'一轮书管理',
							'Books'=>'现金日记账',
							'User'=>'参会人员',
							'Season'=>'场次管理',
							'School'=>'学校管理',
							'Analysis'=>'统计分析',
							'Venue_sales'=>'一轮书信息',
							'Round_analysis'=>'统计分析',
						];
				 break;
		  //分公司信息
      case 'Dept':
                //$info = ['14','15','16','17'];
        $info = ['31','32','33','34','37','38','39','40','41','42','45','47','48','51','52','53','54','55'];
         break;	
         //分公司职位信息
			case 'FPosition':
                //$info = ['14','15','16','17'];
				$info = '0,3,4,5,8,9,20,28,29,31';
				 break;
			  //大区分成标准
			 case 'AreaExtract':
					$info = [
							//标准套数
							'Standard'=>100,
							//小于标准的价格
							'Standard_lt'=>10,
							//大于等于标准的价格
							'Standard_egt'=>25,
							//标准套数150
							'Standard150'=>150,
							//小于标准的价格
							'Standard150_lt'=>0,
							//大于等于标准的价格
							'Standard150_egt'=>40,
							//营销中心总经理固定价格
							'CoreManage'=>20,

						];
                break;
			 //一轮书信息
			 case 'RoundInfo':
					$info = [
							//销售类型
							'Sales_type'=>[
								1=>[
									'name'=>'一轮教案',
									//成本
									'cost'=>25,
								],
								2=>[
									'name'=>'一轮提典',
									'cost'=>15,
								],
								3=>[
									'name'=>'背题本',
									'cost'=>9.5,
								],
								4=>[
									'name'=>'文具',
									'cost'=>15,
								],
							],
							//定价类型
							'Pricing_type'=>[
								1=>'单科定价',
								2=>'组合定价',
							],
							//单科定价
							'Pricing_price'=>[
								98.6,
								108.9,
								38.9,
								58.9,
							],

						];
                break;
				//一轮书分成标准
			 case 'RoundExtract':
					$info = [
							//标准单周销售2986折合数量
							'StandardNum'=>100,
							//标准50折套数
							'StandardNum120'=>120,
							//小于标准的数据
							'StandardNum_lt'=>[
								//经理分成
								'ExtractHis'=>24,
								//副经理分成
								'ExtractDeputyHis'=>6,
								//图书经理分成
								'ExtractBooksHis'=>10,
								//外联分成
								'ExtractOutreachHis'=>0,
								//全体人员（参与人员）
								'ExtractAllHis'=>50,
							],
							//大于等于标准的数据
							'StandardNum_egt'=>[
								//经理分成
								'ExtractHis'=>50,
								//副经理分成
								'ExtractDeputyHis'=>10,
								//图书经理分成
								'ExtractBooksHis'=>10,
								//外联分成
								'ExtractOutreachHis'=>30,
								//全体人员（参与人员）
								'ExtractAllHis'=>50,
							],
						/*
								//小于标准的数据
							'StandardNum_lt'=>[
								//经理分成
								'ExtractHis'=>12,
								//副经理分成
								'ExtractDeputyHis'=>3,
								//图书经理分成
								'ExtractBooksHis'=>5,
								//外联分成
								'ExtractOutreachHis'=>0,
								//全体人员（参与人员）
								'ExtractAllHis'=>50,
							],
							//大于等于标准的数据
							'StandardNum_egt'=>[
								//经理分成
								'ExtractHis'=>25,
								//副经理分成
								'ExtractDeputyHis'=>5,
								//图书经理分成
								'ExtractBooksHis'=>5,
								//外联分成
								'ExtractOutreachHis'=>15,
								//全体人员（参与人员）
								'ExtractAllHis'=>50,
							],
							*/
						];
                break;
			//一轮书公司收回标准
			 case 'CompanyExtract':
					$info = [
							'Company50'=>50,
							'Company55'=>55,
							'Company60'=>60,
							
						];
                break;
                //一轮书公司收回标准
       case 'Tool':
          $info = [
              //分享
              'Source'=>[
                1=>[
                    'name'=>'招募令',
                    //海报图片类型
                    'hb_type'=>2,
                    //分享链接
                    'url'=>'http://tmall.fc62.com/zhaomu.php?source=xxx',
                  ],
                2=>[
                    'name'=>'预售考前猜题卷',
                    //海报图片类型
                    'hb_type'=>1,
                    //分享链接
                    'url'=>'https://oa.fc62.com/index/ques/sale/ids/xxx',
                  ],
              ]
            ];
                break;
            default:
				$info = '';
                break;
        }
        return $info;
    }
}
if (!function_exists('http_post')) {
    function http_post($url, $param=[], $post_file = false)
    {
        $oCurl = curl_init();

        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }

        if ($post_file) {
            if ($is_curlFile) {
                foreach ($param as $key => $val) {
                    if (isset($val["tmp_name"])) {
                        $param[$key] = new \CURLFile(realpath($val["tmp_name"]), $val["type"], $val["name"]);
                    } else if (substr($val, 0, 1) == '@') {
                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));
                    }
                }
            }
            $strPOST = $param;
        } else {
            $strPOST = json_encode($param);
        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
        curl_setopt($oCurl, CURLOPT_HEADER, 1);

        // $sContent = curl_exec($oCurl);
        // $aStatus  = curl_getinfo($oCurl);

        $sContent = execCURL($oCurl);
        curl_close($oCurl);

        return $sContent;
    }
}
if (!function_exists('execCURL')) {

    function execCURL($ch)
    {
        $response = curl_exec($ch);
        $error = curl_error($ch);
        $result = array('header' => '',
            'content' => '',
            'curl_error' => '',
            'http_code' => '',
            'last_url' => '');

        if ($error != "") {
            $result['curl_error'] = $error;
            return $result;
        }

        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $result['header'] = str_replace(array("\r\n", "\r", "\n"), "<br/>", substr($response, 0, $header_size));
        $result['content'] = substr($response, $header_size);
        $result['http_code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
        $result["base_resp"] = array();
        $result["base_resp"]["ret"] = $result['http_code'] == 200 ? 0 : $result['http_code'];
        $result["base_resp"]["err_msg"] = $result['http_code'] == 200 ? "ok" : $result["curl_error"];

        return $result['base_resp'];
    }
}
if (!function_exists('pushMsgText')) {
    /**
     * @param $config
     * @param $msg
     * @param $userId 成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为@all，则向该企业应用的全部成员发送
     * @param int $sale  表示是否是保密消息，0表示否，1表示是，默认0
     * @param string $departmentId 部门ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数
     * @param string $tagId 标签ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数
     * @param string $msgtype 消息类型
     * @param string $content 内容
     * @return array|string
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    function pushMsgText($config,$msgtype='text',$content=[],$userId = NULL, $departmentId = NULL,$tagId = NULL,$sale = 0,$enable_id_trans = 0,$enable_duplicate_check = 0)
    {
        $app = Factory::work($config);
        $token = $app->access_token->getToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
        $msg = array(
            'touser'=>$userId,
            'toparty'=>$departmentId,//部门ID
            'totag'=>$tagId,//标签ID
            'msgtype'=>$msgtype,
            'agentid'=>$config['agent_id'],
            $msgtype=>$content,
            "safe"=>$sale,
            "enable_id_trans"=>$enable_id_trans,
            "enable_duplicate_check"=>$enable_duplicate_check
        );
        write_log($msg,'',4,'wechat_notice');
        return http_post($url,$msg);
    }
}
if (!function_exists('excelToArray')) {
   /** 
    *   方法名 :   excelToArray 
    *   @date   :    2019/4/25
    *   @author :    gzy 
    */    
    function excelToArray($filePath,$info = []){  
                $fieldArr = excelArray();
               //print_r($fieldArr);die;
               $PHPReader = new \PHPExcel_Reader_Excel2007();
                if (!$PHPReader->canRead($filePath)) {
                    $PHPReader = new \PHPExcel_Reader_Excel5();
                    if (!$PHPReader->canRead($filePath)) {
                        $PHPReader = new \PHPExcel_Reader_CSV();
                        if (!$PHPReader->canRead($filePath)) {
                            $this->error(__('Unknown data format'));
                        }
                    }
                }
                $PHPExcel = $PHPReader->load($filePath); //加载文件
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
                for ($currentRow = 3; $currentRow <= 3; $currentRow++) {
                    for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = $val;
                    }
                }
                //基本信息
                $insert = [];
                //发放信息
                $insert2 = [];
                //工资月份
                $years = 0;
                if($info['import_type'] == 2){
                   $years = strtotime($info['year'].'-'.$info['month']);
                }
            
                for ($currentRow = 4; $currentRow <= $allRow; $currentRow++) {
                    $import_type = $info['import_type'];
                    $additional = [];
                    $values = [];
                    for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];
                    $row1 = [];
                    $row2= [];
                    $temp = array_combine($fields, $values);
                  
                    foreach ($temp as $k => $v) {
                        if (isset($fieldArr[$k]) && $k !== '') {
                            $row[$fieldArr[$k]['key']]['value'] = $v;
                            $row[$fieldArr[$k]['key']]['role'] = $fieldArr[$k]['role'];
                            $row[$fieldArr[$k]['key']]['name'] = $k;
                        }
                    }

                    if($row){
                         //去除空格圆角符号
                         $row['id_number']['value'] = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/","", $row['id_number']['value']);
                         if(!$userid = TableField('Admin','userid',$row['id_number']['value'],'id_number')) continue;
                         if($info['import_type'] == 2){
                          
                             if(!$userid1 = TableField('Wageslist','userid',$userid,'userid')){
                                $import_type = 1;
                             }
                             $additional['years'] = $years;
                             if($id = TableField('Wages','id',$userid,'userid',$additional)){
                                $row2['id'] = $id;
                             }
                         }
                         if($info['import_type'] == 1){
                             if($id = TableField('Wageslist','id',$userid,'userid')){
                                $row1['id'] = $id;
                             }
                         }
                        //基本信息
                        if($info['import_type'] == 1 || $import_type == 1){
                            $row1['userid'] = $userid;
                            foreach($row as $k=>$v){
                                if($v['role'] == 1 || $v['role'] == 3){
                                    $row1[$k] = $v['value'];
                                }
                            }

                         }
                         //发放信息
                         if($info['import_type'] == 2 || $import_type == 2){
                             $row2['userid'] = $userid;
                             foreach($row as $k=>$v){
                                if($v['role'] == 2 || $v['role'] == 3){
                                    $row2[$k] = $v['value'];
                                }
                             }
                             $row2['years'] = $years;
                          }
                        if($row1) $insert[] = $row1;
                        if($row2) $insert2[] = $row2;
                         unset($row,$userid,$userid1,$id);
                     }
                   
                }
                if(!empty($insert)){ 
                    $result = model(GetTableModel('Wageslist'))->saveAll($insert);
                }
                if(!empty($insert2)){ 
                    $result2 = model(GetTableModel('Wages'))->saveAll($insert2);
                }
             return true;
    }
}
if (!function_exists('ExcelWagesAll')) {
    /**
     * 导出数据 
     * @return array
     * @author gzy
     * @time 2019年5月10日 14:14:30
     */
    function ExcelWagesAll($date = []){
    
       if(empty($date)) return false;
         set_time_limit(0);
        $excel = new PHPExcel();
        $years = strtotime($date['year'].'-'.$date['month']);
        $where = "b.years = '".$years."'";
        $info = \think\Db::name('wageslist')->alias('a')
        ->field("b.*,a.education,a.major,a.entry_date,a.become_date,a.work_years")
        ->join('wages b','a.userid = b.userid')
        ->where($where)
        ->select();
       
        $total = [];
        $a = 0;
        $list = [];
        $title = $date['year'].'年'.$date['month'].'月份工资信息';
        foreach($info as $key=>$val){
            $val['name'] = TableField('Admin','username',$val['userid'],'userid');
            $val['id_number'] = TableField('Admin','id_number',$val['userid'],'userid');
            $val['achievements_royaltyTotal'] = $val['overtime_royalty']+$val['achievements_royalty'];
            $list[$val['id']] = $val;
        }
        if(empty($list)) return false;
         $excel->getProperties()
            ->setCreator("gzy")
            ->setLastModifiedBy("gzy")
            ->setTitle($title)
            ->setSubject($title);
       //从第几行开始
       $line = 3;
       $styleArray = array(
             'font' => array(
                    'size'  => 10,
                    'name'  => 'Verdana'
             ),
              'borders' => array(
                    'allborders' => array( //设置全部边框
                        'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
                    ),

                ),
       );
        $worksheet = $excel->setActiveSheetIndex($a);
        $excel->getActiveSheet()->mergeCells('A1:AN1');//合并第一行的单元格
        $excel->getActiveSheet()->mergeCells('A2:AN2');//合并第二行的单元格
        $excel->setActiveSheetIndex($a)->setCellValue('A1','北京宏达一甲教育科技有限公司');//标题 
        $excel->setActiveSheetIndex($a)->setCellValue('A2',$title);//标题
        $excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $excel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $excel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);  
        $sss = 0;
        foreach(excelArray() as $kk=>$vv){
            if($vv['role']>4) continue;
            $worksheet->setCellValueByColumnAndRow($sss, $line, $kk);
            $excel->getActiveSheet()-> getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($sss))->setWidth($vv['width']);
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $sss++;
        }
        
        $worksheet->setTitle($title);
        $mynum = 1;//序号
        foreach ($list as $index => $item) {
                    $line++;
                    $sss = 0;
                    foreach(excelArray() as $kk=>$vv){
                        if($vv['role']>4) continue;
                        if($vv['key'] == 'mynum'){
                            $worksheet->setCellValueByColumnAndRow($sss, $line, $mynum);
                        }elseif($vv['key'] == 'id_number'){
                            $worksheet->setCellValueByColumnAndRow($sss, $line, $item[$vv['key']]."\t");
                        }else{
                            $worksheet->setCellValueByColumnAndRow($sss, $line, $item[$vv['key']]);
                        }
                        $worksheet->getStyleByColumnAndRow($sss,$line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                        $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
                        $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                        //$worksheet->getColumnDimension($sss)->setWidth(50);;
                        $sss++;
                    }
                $mynum++;
            }
        $line = $line+1;
       //合计
        $sss = 0;
        foreach(excelArray() as $kk=>$vv){
            if($vv['role']>4) continue;
            if($vv['type'] == 2){
                $vss = [];
                $vss[] = $vv['key'];
                for($aa = 0;$aa<count($list);$aa++){
                    $vss[$aa] = $vv['key'];
                }
                $total[$vv['key']] = array_sum(array_map(create_function('$val,$vv', 'return $val[$vv];'), $list,$vss));
              
            }
            $worksheet->setCellValueByColumnAndRow($sss, $line, $total[$vv['key']]??'');
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $sss++;
        }
        $excel->getActiveSheet()->mergeCells('A'.$line.':H'.$line.'');//合并第一行的单元格
        $excel->getActiveSheet()->getStyle('A'.$line.'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $excel->setActiveSheetIndex($a)->setCellValue('A'.$line.'', '合计');//标题
        //print_R($total);die;
        $excel->createSheet();
        //删除空的sheet
        $sheetIndex = $excel->getIndex($excel->getSheetByName('Worksheet')); 
        if($sheetIndex) $excel->removeSheetByIndex($sheetIndex);
        return $excel;
    }
}
if (!function_exists('excelToArrayRoyalty')) {
   /** 
    *   方法名 :   excelToArrayRoyalty 
    *   @date   :    2019/5/17
    *   @author :    gzy 
    */    
    function excelToArrayRoyalty($filePath,$info = []){  
                $fieldArr = excelArray(2);
               //print_r($fieldArr);die;
               $PHPReader = new \PHPExcel_Reader_Excel2007();
                if (!$PHPReader->canRead($filePath)) {
                    $PHPReader = new \PHPExcel_Reader_Excel5();
                    if (!$PHPReader->canRead($filePath)) {
                        $PHPReader = new \PHPExcel_Reader_CSV();
                        if (!$PHPReader->canRead($filePath)) {
                            $this->error(__('Unknown data format'));
                        }
                    }
                }
                $PHPExcel = $PHPReader->load($filePath); //加载文件
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                // $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
                $maxColumnNumber = 23;
                for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                    for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = preg_replace("/((0|[1-9]\d*)(\.\d+)?)|(-|月)/", "", $val);
                    }
                }

                //基本信息
                $insert = [];
                //发放信息
                $insert2 = [];
                //工资月份
                $years = [];
                $start_time = '';
                $end_time = '';
                if($info['import_type'] == 2){
                   $years = explode(',', $info['date']);
                   $start_time = $years[0];
                   $end_time = $years[1];
                }
           
                for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                    $import_type = $info['import_type'];
                    $additional = [];
                    $values = [];
                    for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];
                    $row1 = [];
                    $row2= [];
                    $temp = array_combine($fields, $values);
                  
                    foreach ($temp as $k => $v) {
                        if (isset($fieldArr[$k]) && $k !== '') {
                            $row[$fieldArr[$k]['key']]['value'] = $v;
                            $row[$fieldArr[$k]['key']]['role'] = $fieldArr[$k]['role'];
                            $row[$fieldArr[$k]['key']]['name'] = $k;
                        }
                    }
 
                    if($row){
                         //去除空格圆角符号
                         $row['id_number']['value'] = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/","", $row['id_number']['value']);
                         if(!$userid = TableField('Admin','userid',$row['id_number']['value'],'id_number')) continue;

                         if($info['import_type'] == 2){
                             if(!$userid1 = TableField('Admininfo','userid',$userid,'userid')){
                                $import_type = 1;
                             }
                             $row2['start_time'] = $additional['start_time'] = $start_time;
                             $row2['end_time'] = $additional['end_time'] = $end_time;
                             // print_r(TableField('Info','id',$userid,'userid',$additional));die;
                             $row2['z_publish'] = $row2['publish'] = \think\Session::get('admin')['userid'];
                             if($id = TableField('Info','id',$userid,'userid',$additional)){
                                $row2['id'] = $id;
                                unset($row1['publish']);
                             }
                         }
                         if($info['import_type'] == 1){
                            $row1['z_publish'] = $row1['publish'] = \think\Session::get('admin')['userid'];
                             if($id = TableField('Admininfo','id',$userid,'userid')){
                                $row1['id'] = $id;
                                unset($row1['publish']);
                              
                             }
                         }
                        //基本信息
                        if($info['import_type'] == 1 || $import_type == 1){
                            $row1['userid'] = $userid;
                            if($import_type == 1){
                               $row1['z_publish'] = $row1['publish'] = \think\Session::get('admin')['userid'];
                            }
                            foreach($row as $k=>$v){
                                if($v['role'] == 1 || $v['role'] == 3){
                                    $row1[$k] = $v['value'];
                                }
                            }

                         }
                         //发放信息
                         if($info['import_type'] == 2 || $import_type == 2){
                             $row2['userid'] = $userid;
                             foreach($row as $k=>$v){
                                if($v['role'] == 2 || $v['role'] == 3){
                                    $row2[$k] = $v['value'];
                                }
                             }
                          }
                        if($row1) $insert[] = $row1;
                        if($row2) $insert2[] = $row2;
                         unset($row,$userid,$userid1,$id);
                     }
                   
                }
                if(!empty($insert)){ 
                    $result = model(GetTableModel('Admininfo'))->saveAll($insert);
                }
                if(!empty($insert2)){ 
                    $result2 = model(GetTableModel('Info'))->saveAll($insert2);
                }
             return true;
    }
}
if (!function_exists('ExcelInfoAll')) {
    /**
     * 导出数据 
     * @return array
     * @author gzy
     * @time 2019年5月17日 17:24:33
     */
    function ExcelInfoAll($date = []){
    
       if(empty($date)) return false;
         set_time_limit(0);
        $excel = new PHPExcel();
        $years = explode(',', $date['date']);
        $where = "b.start_time = '".$years[0]."' and b.end_time = '".$years[1]."'";
        $info = \think\Db::name('admin_info')->alias('a')
        ->field("b.*")
        ->join('finance_extract_info b','a.userid = b.userid')
        ->where($where)
        ->order('b.weigh asc')
        ->select();
        $total = [];
        $a = 0;
        $list = [];
        $title = $date['date'].'提成信息';
        
         $data = [];
        foreach($info as $key=>$val){
            $data = TableField('Admin','username',$val['userid'],'userid',[],2);
            if($data){
              $val['name'] = $data['username'];
              $val['id_number'] = $data['id_number'];
              $val['mobile'] = $data['mobile'];
              $val['department'] = $data['department_text'];
              $val['position'] = $data['position'];
            }
            $list[$val['id']] = $val;
            unset($data);
        }
        if(empty($list)) return false;
         $excel->getProperties()
            ->setCreator("gzy")
            ->setLastModifiedBy("gzy")
            ->setTitle($title)
            ->setSubject($title);
       //从第几行开始
       $line = 2;
       $styleArray = array(
             'font' => array(
                    'size'  => 10,
                    'name'  => 'Verdana'
             ),
              'borders' => array(
                    'allborders' => array( //设置全部边框
                        'style' => \PHPExcel_Style_Border::BORDER_THIN //粗的是thick
                    ),

                ),
       );
        $worksheet = $excel->setActiveSheetIndex($a);
        $excel->getActiveSheet()->mergeCells('A1:W1');//合并第一行的单元格
        $excel->setActiveSheetIndex($a)->setCellValue('A1',$title);//标题 
        $excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $excel->getActiveSheet()->getRowDimension('1')->setRowHeight(20);  
        $sss = 0;
        foreach(excelArray(2) as $kk=>$vv){
            if($vv['role']>4) continue;
            $worksheet->setCellValueByColumnAndRow($sss, $line, $kk);
            $excel->getActiveSheet()-> getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($sss))->setWidth($vv['width']);
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $sss++;
        }
        $worksheet->setTitle($title);
        foreach ($list as $index => $item) {
                    $line++;
                    $sss = 0;
                    foreach(excelArray(2) as $kk=>$vv){
                        if($vv['role']>4) continue;
                      if($vv['key'] == 'id_number'){
                            $worksheet->setCellValueByColumnAndRow($sss, $line, $item[$vv['key']]."\t");
                        }else{
                            $worksheet->setCellValueByColumnAndRow($sss, $line, $item[$vv['key']]);
                        }
                        $worksheet->getStyleByColumnAndRow($sss,$line)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
                        $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
                        $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                        //$worksheet->getColumnDimension($sss)->setWidth(50);;
                        $sss++;
                    }
            
            }
        $line = $line+1;
       //合计
        $sss = 0;
        foreach(excelArray(2) as $kk=>$vv){
            if($vv['role']>4) continue;
            if($vv['type'] == 2){
                $vss = [];
                $vss[] = $vv['key'];
                for($aa = 0;$aa<count($list);$aa++){
                    $vss[$aa] = $vv['key'];
                }
                $total[$vv['key']] = array_sum(array_map(create_function('$val,$vv', 'return $val[$vv];'), $list,$vss));
              
            }
            $worksheet->setCellValueByColumnAndRow($sss, $line, $total[$vv['key']]??'');
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->applyFromArray($styleArray);
            $worksheet->getCellByColumnAndRow($sss, $line)->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $sss++;
        }
        $excel->getActiveSheet()->mergeCells('A'.$line.':E'.$line.'');//合并第一行的单元格
        $excel->getActiveSheet()->getStyle('A'.$line.'')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $excel->setActiveSheetIndex($a)->setCellValue('A'.$line.'', '合计');//标题
        //print_R($total);die;
        $excel->createSheet();
        //删除空的sheet
        $sheetIndex = $excel->getIndex($excel->getSheetByName('Worksheet')); 
        if($sheetIndex) $excel->removeSheetByIndex($sheetIndex);
        return $excel;
    }
}
if (!function_exists('excelArray')) {
    /** 
    *   方法名 :   excelArray 
    role=1 基本信息  =2 发放信息 =3 公共信息 >4 导出不展现  =0其他信息
    width 宽度
    tyoe=1 默认展示 =2 需要计算合并  导出才判断type
    *   @date   :    2019/4/25
    *   @author :    gzy 
    */    
    function excelArray($type = 1)
    {
        $arr1 = [
               '学历' => [
                    'key'=>'education',
                    'role'=>1,
                    'width'=>10,
                    'type'=>1,
                ],
                '专业' =>  [
                    'key'=>'major',
                    'role'=>1,
                    'width'=>10,
                    'type'=>1,
                ],
                '序号' => [
                    'key'=>'mynum',
                    'role'=>0,
                    'width'=>5,
                    'type'=>1,
                ], 
                '姓名' => [
                    'key'=>'name',
                    'role'=>0,
                    'width'=>8,
                    'type'=>1,
                ], 
                '身份证号' => [
                    'key'=>'id_number',
                    'role'=>0,
                    'width'=>30,
                    'type'=>1,
                ], 
                '工龄' => [
                    'key'=>'work_years',
                    'role'=>1,
                    'width'=>5,
                    'type'=>2,
                ],
                '工资月份' => [
                    'key'=>'years',
                    'role'=>5,
                    'width'=>8,
                    'type'=>1,
                ],
                '入职日期' => [
                    'key'=>'entry_date',
                    'role'=>1,
                    'width'=>15,
                    'type'=>1,
                ],
                '转正日期' => [
                    'key'=>'become_date',
                    'role'=>1,
                    'width'=>15,
                    'type'=>1,
                ],
               '应出勤天数' => [
                    'key'=>'attendance',
                    'role'=>2,
                    'width'=>15,
                    'type'=>1,
                ],
                '基本工资' => [
                    'key'=>'basic_wages',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                
                 '话费补贴' => [
                    'key'=>'tel_wages',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                '交通补贴' => [
                    'key'=>'traffic_wages',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                '优秀员工补贴' => [
                    'key'=>'best_wages',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                 '工龄补贴' => [
                    'key'=>'length_wages',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                '餐补' => [
                    'key'=>'meal_wages',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '其他补贴' => [
                    'key'=>'other_wages',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '扣款' => [
                    'key'=>'charged',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '应发工资' => [
                    'key'=>'should_wages',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '养老保险费' => [
                    'key'=>'pension_sure',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                '医疗保险费' => [
                    'key'=>'health_sure',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                '失业保险费' => [
                    'key'=>'out_sure',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                '住房公积金' => [
                    'key'=>'home_sure',
                    'role'=>3,
                    'width'=>15,
                    'type'=>2,
                ],
                '个税' => [
                    'key'=>'one_tax',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '补扣、多扣税额' => [
                    'key'=>'repair_tax',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '现金工资' => [
                    'key'=>'cash_wages',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ], 
                '银行实发工资' => [
                    'key'=>'bank_wages',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '应发合计' => [
                    'key'=>'total_wages',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '加班版税' => [
                    'key'=>'overtime_royalty',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '绩效版税' => [
                    'key'=>'achievements_royalty',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
               '绩效版税合计' => [
                    'key'=>'achievements_royaltyTotal',
                    'role'=>0,
                    'width'=>15,
                    'type'=>2,
                ], 
                '非销版税' => [
                    'key'=>'nonsale_royalty',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '版税合计' => [
                    'key'=>'total_royalty',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '事假扣款' => [
                    'key'=>'thing_charged',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '病假扣款' => [
                    'key'=>'illness_charged',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '旷工扣款' => [
                    'key'=>'absenteeism_charged',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '迟到扣款' => [
                    'key'=>'late_charged',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '应发版税' => [
                    'key'=>'should_royalty',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '版税税金' => [
                    'key'=>'royalty_tax',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '版税实发' => [
                    'key'=>'realhair_royalty',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '备注' => [
                    'key'=>'desc',
                    'role'=>2,
                    'width'=>15,
                    'type'=>1,
                ],    
            ];
        $arr2 = [
                '序号' => [
                    'key'=>'weigh',
                    'role'=>3,
                    'width'=>5,
                    'type'=>1,
                ],      
                 '部门' => [
                    'key'=>'department',
                    'role'=>0,
                    'width'=>15,
                    'type'=>1,
                ],       
                 '岗位' => [
                    'key'=>'position',
                    'role'=>0,
                    'width'=>10,
                    'type'=>1,
                ],    
                '姓名' => [
                    'key'=>'name',
                    'role'=>0,
                    'width'=>8,
                    'type'=>1,
                ], 
                '身份证号' => [
                    'key'=>'id_number',
                    'role'=>0,
                    'width'=>30,
                    'type'=>1,
                ], 
                '周销售版税' => [
                    'key'=>'point_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                '周建群+进直播间提成版税' => [
                    'key'=>'later_on',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
                // '周奖励' => [
                //     'key'=>'bonus',
                //     'role'=>2,
                //     'width'=>15,
                //     'type'=>2,
                // ],  
                '周会后一轮书版税' => [
                    'key'=>'books_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],   
                 '周一轮书定数版税' => [
                    'key'=>'fixed_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],   
                 '周绘本课堂版税' => [
                    'key'=>'picture_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ], 
               
                 '周签约版税' => [
                    'key'=>'contract_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],      
                '周股份版税' => [
                    'key'=>'shares_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],        
                '参会费' => [
                    'key'=>'admission_fee',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ], 
                 '版税合计' => [
                    'key'=>'week_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],    
                '本周扣税' => [
                    'key'=>'tax_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],     
                '欠缴税金' => [
                    'key'=>'tax_owe',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],     
               '补缴税金' => [
                    'key'=>'no_tax_owe',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],  
                 '上周未扣无票' => [
                    'key'=>'s_no_ticket_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],    
                '本周需扣无票' => [
                    'key'=>'s_no_ticket_owe',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],   
                 '无票合计' => [
                    'key'=>'no_ticket_total',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],    
                 '本周已扣无票' => [
                    'key'=>'no_ticket_noowe',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],   
               '本周未扣无票' => [
                    'key'=>'no_ticket_owe',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],  
                '扣税金、参会版税及无票实发版税' => [
                    'key'=>'real_hair',
                    'role'=>2,
                    'width'=>15,
                    'type'=>2,
                ],
               // '电话号码' => [
               //      'key'=>'mobile',
               //      'role'=>0,
               //      'width'=>15,
               //      'type'=>1,
               //  ],
            ];
        if($type == 1){
            return $arr1;
        }else{
            return $arr2;
        }
    }
}
if(!function_exists('isMobile'))
{
    function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
        {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            }
        }
        return false;
    }
}




